"use client";

import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { Alert, Button, Card, Descriptions, Spin, Tag, Typography } from "antd";
import { ArrowLeftOutlined, InboxOutlined } from "@ant-design/icons";

import { CmsSectionTitle } from "@/components/admin/CmsSectionTitle";

const apiBase = () => process.env.NEXT_PUBLIC_API_BASE_URL ?? "";

type Detail = {
  id: string;
  orderId: string;
  assignedToUserId: string | null;
  status: string;
  priority: string;
  dueAt: string | null;
  internalNotes: string | null;
  customerVisibleNotes: string | null;
  createdAt: string;
  updatedAt: string;
  order: {
    id: string;
    status: string;
    packageKey: string;
    userId: string | null;
    email: string | null;
    phone: string | null;
  };
};

export default function PremiumFulfillmentTaskDetailPage() {
  const params = useParams();
  const router = useRouter();
  const id = typeof params?.id === "string" ? params.id : "";
  const [row, setRow] = useState<Detail | null>(null);
  const [err, setErr] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    if (!id) return;
    setLoading(true);
    setErr(null);
    const token =
      typeof window !== "undefined" ? window.localStorage.getItem("accessToken") : null;
    if (!token) {
      setErr("Not signed in.");
      setRow(null);
      setLoading(false);
      return;
    }
    const res = await fetch(`${apiBase()}/internal/premium-fulfillment-tasks/${id}`, {
      headers: { Authorization: `Bearer ${token}` },
    });
    if (res.status === 403) {
      setErr("Not allowed (AUTHOR: only your assigned tasks).");
      setRow(null);
      setLoading(false);
      return;
    }
    if (!res.ok) {
      setErr(`Request failed (${res.status}).`);
      setRow(null);
      setLoading(false);
      return;
    }
    setRow((await res.json()) as Detail);
    setLoading(false);
  }, [id]);

  useEffect(() => {
    void load();
  }, [load]);

  return (
    <Card className="cms-surface-card" styles={{ body: { padding: "24px 28px" } }}>
      <Button
        type="text"
        icon={<ArrowLeftOutlined />}
        className="!mb-4 !text-indigo-200/80"
        onClick={() => router.push("/dashboard/premium-fulfillment-tasks")}
      >
        Back
      </Button>
      <CmsSectionTitle
        icon={<InboxOutlined />}
        title="Fulfillment task"
        description="Internal fields including internal notes — staff only."
      />
      {err ? <Alert type="warning" message={err} showIcon className="mb-4" /> : null}
      {loading ? (
        <div className="py-16 text-center">
          <Spin />
        </div>
      ) : row ? (
        <>
          <Descriptions column={1} size="small" bordered className="!mb-4">
            <Descriptions.Item label="Task ID">{row.id}</Descriptions.Item>
            <Descriptions.Item label="Status">
              <Tag color="blue">{row.status}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="Priority">{row.priority}</Descriptions.Item>
            <Descriptions.Item label="Order">
              <Link href="/dashboard/premium-orders" className="text-indigo-300">
                {row.orderId}
              </Link>{" "}
              <Tag>{row.order.status}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="Package">{row.order.packageKey}</Descriptions.Item>
            <Descriptions.Item label="Assignee">{row.assignedToUserId ?? "—"}</Descriptions.Item>
            <Descriptions.Item label="Due">{row.dueAt ?? "—"}</Descriptions.Item>
            <Descriptions.Item label="Customer-visible notes">
              <Typography.Paragraph className="!mb-0 whitespace-pre-wrap">
                {row.customerVisibleNotes ?? "—"}
              </Typography.Paragraph>
            </Descriptions.Item>
            <Descriptions.Item label="Internal notes">
              <Typography.Paragraph className="!mb-0 whitespace-pre-wrap text-amber-200/90">
                {row.internalNotes ?? "—"}
              </Typography.Paragraph>
            </Descriptions.Item>
          </Descriptions>
          <Typography.Text type="secondary" className="text-xs">
            Updated {row.updatedAt}
          </Typography.Text>
        </>
      ) : null}
    </Card>
  );
}
