"use client";

import { useCallback, useEffect, useState } from "react";
import { Alert, Card, Spin, Table, Typography, Tag } from "antd";
import { ShoppingOutlined } from "@ant-design/icons";

import { CmsSectionTitle } from "@/components/admin/CmsSectionTitle";

const apiBase = () => process.env.NEXT_PUBLIC_API_BASE_URL ?? "";

type OrderRow = {
  id: string;
  status: string;
  packageKey: string;
  email: string | null;
  phone: string | null;
  userId: string | null;
  savedReadingId: string | null;
  createdAt: string;
};

export default function PremiumOrdersListPage() {
  const [items, setItems] = useState<OrderRow[]>([]);
  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-orders?limit=80`, {
      headers: { Authorization: `Bearer ${token}` },
    });
    if (res.status === 403) {
      setErr("MANAGER or SUPER_ADMIN required.");
      setItems([]);
      setLoading(false);
      return;
    }
    if (!res.ok) {
      setErr(`Request failed (${res.status}).`);
      setItems([]);
      setLoading(false);
      return;
    }
    const body = (await res.json()) as { items?: OrderRow[] };
    setItems(body.items ?? []);
    setLoading(false);
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  return (
    <Card className="cms-surface-card" styles={{ body: { padding: "24px 28px" } }}>
      <CmsSectionTitle
        icon={<ShoppingOutlined />}
        title="Premium Tu Vi orders"
        description="Manual / offline workflow — no live checkout. See docs/launch/payment-readiness-and-premium-orders.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: "ID", dataIndex: "id", key: "id", ellipsis: true },
            {
              title: "Status",
              dataIndex: "status",
              key: "status",
              width: 130,
              render: (s: string) => <Tag color="blue">{s}</Tag>,
            },
            { title: "Package", dataIndex: "packageKey", key: "packageKey", width: 160 },
            { title: "Email", dataIndex: "email", key: "email", ellipsis: true },
            { title: "Phone", dataIndex: "phone", key: "phone", width: 120 },
            { title: "Saved", dataIndex: "savedReadingId", key: "savedReadingId", ellipsis: true },
          ]}
        />
      )}
      <Typography.Paragraph className="!mt-4 !mb-0 text-xs text-white/45">
        Update status via API: PATCH /internal/premium-orders/:id/status with JSON{" "}
        <code className="text-[11px]">{`{"status":"CONTACTED"}`}</code>.
      </Typography.Paragraph>
    </Card>
  );
}
