"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { Alert, Card, Spin, Table, Tag, Typography } from "antd";
import { InboxOutlined } from "@ant-design/icons";

import { CmsSectionTitle } from "@/components/admin/CmsSectionTitle";

const apiBase = () => process.env.NEXT_PUBLIC_API_BASE_URL ?? "";

type TaskRow = {
  id: string;
  orderId: string;
  status: string;
  priority: string;
  assignedToUserId: string | null;
  dueAt: string | null;
  updatedAt: string;
};

export default function PremiumFulfillmentTasksPage() {
  const [items, setItems] = useState<TaskRow[]>([]);
  const [err, setErr] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    setErr(null);
    const token =
      typeof window !== "undefined" ? window.localStorage.getItem("accessToken") : null;
    if (!token) {
      setErr("Not signed in.");
      setItems([]);
      setLoading(false);
      return;
    }
    const res = await fetch(`${apiBase()}/internal/premium-fulfillment-tasks?limit=100`, {
      headers: { Authorization: `Bearer ${token}` },
    });
    if (res.status === 403) {
      setErr("MANAGER, SUPER_ADMIN, or AUTHOR (assigned tasks only) required.");
      setItems([]);
      setLoading(false);
      return;
    }
    if (!res.ok) {
      setErr(`Request failed (${res.status}).`);
      setItems([]);
      setLoading(false);
      return;
    }
    const body = (await res.json()) as { items?: TaskRow[] };
    setItems(body.items ?? []);
    setLoading(false);
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  return (
    <Card className="cms-surface-card" styles={{ body: { padding: "24px 28px" } }}>
      <CmsSectionTitle
        icon={<InboxOutlined />}
        title="Premium fulfillment tasks"
        description="Manual queue for premium Tu Vi delivery — see docs/launch/premium-fulfillment-workflow.md."
      />
      {err ? <Alert type="warning" message={err} showIcon className="mb-4" /> : null}
      {loading ? (
        <div className="py-16 text-center">
          <Spin />
        </div>
      ) : (
        <Table
          rowKey="id"
          size="small"
          pagination={false}
          dataSource={items}
          columns={[
            {
              title: "Task",
              dataIndex: "id",
              key: "id",
              ellipsis: true,
              render: (id: string) => (
                <Link href={`/dashboard/premium-fulfillment-tasks/${id}`} className="text-indigo-300">
                  {id}
                </Link>
              ),
            },
            {
              title: "Order",
              dataIndex: "orderId",
              key: "orderId",
              ellipsis: true,
            },
            {
              title: "Status",
              dataIndex: "status",
              key: "status",
              width: 150,
              render: (s: string) => <Tag color="blue">{s}</Tag>,
            },
            {
              title: "Priority",
              dataIndex: "priority",
              key: "priority",
              width: 100,
            },
            {
              title: "Assignee",
              dataIndex: "assignedToUserId",
              key: "assignedToUserId",
              ellipsis: true,
            },
          ]}
        />
      )}
      <Typography.Paragraph className="!mt-4 !mb-0 text-xs text-white/45">
        Mutations: POST/PATCH <code className="text-[11px]">/internal/premium-fulfillment-tasks</code> (MANAGER or
        SUPER_ADMIN). AUTHORS see only assigned rows.
      </Typography.Paragraph>
    </Card>
  );
}
