"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { Alert, Card, Col, Row, Spin, Statistic, Table, Tag, Typography } from "antd";
import { AuditOutlined } from "@ant-design/icons";

import { CmsSectionTitle } from "@/components/admin/CmsSectionTitle";

const apiBase = () => process.env.NEXT_PUBLIC_API_BASE_URL ?? "";

type OverviewBody = {
  counts: {
    requestedOrders: number;
    contactedOrders: number;
    paidOfflineOrders: number;
    openFulfillmentTasks: number;
    pendingExpertReviews: number;
    readyDeliveryArtifacts: number;
  };
  queues: {
    recentOrders: Array<Record<string, unknown>>;
    urgentTasks: Array<Record<string, unknown>>;
    pendingReviews: Array<Record<string, unknown>>;
    readyDeliveries: Array<Record<string, unknown>>;
  };
};

export default function PremiumOpsOverviewPage() {
  const [data, setData] = useState<OverviewBody | null>(null);
  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.");
      setData(null);
      setLoading(false);
      return;
    }
    const res = await fetch(`${apiBase()}/internal/premium-ops/overview`, {
      headers: { Authorization: `Bearer ${token}` },
    });
    if (res.status === 403) {
      setErr("MANAGER or SUPER_ADMIN required.");
      setData(null);
      setLoading(false);
      return;
    }
    if (!res.ok) {
      setErr(`Request failed (${res.status}).`);
      setData(null);
      setLoading(false);
      return;
    }
    setData((await res.json()) as OverviewBody);
    setLoading(false);
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  return (
    <div className="space-y-6">
      <Card className="cms-surface-card" styles={{ body: { padding: "24px 28px" } }}>
        <CmsSectionTitle
          icon={<AuditOutlined />}
          title="Premium Ops Overview"
          description="Beta handoff — counts and short queues. See docs/launch/premium-ops-workflow.md."
        />
        {err ? <Alert type="warning" message={err} showIcon className="mb-4" /> : null}
        {loading ? (
          <div className="py-16 text-center">
            <Spin />
          </div>
        ) : data ? (
          <>
            <Row gutter={[16, 16]} className="mb-6">
              <Col xs={24} sm={12} md={8} lg={8}>
                <Card size="small" className="!bg-white/[0.04] !border-white/10">
                  <Statistic title="Orders · REQUESTED" value={data.counts.requestedOrders} />
                </Card>
              </Col>
              <Col xs={24} sm={12} md={8} lg={8}>
                <Card size="small" className="!bg-white/[0.04] !border-white/10">
                  <Statistic title="Orders · CONTACTED" value={data.counts.contactedOrders} />
                </Card>
              </Col>
              <Col xs={24} sm={12} md={8} lg={8}>
                <Card size="small" className="!bg-white/[0.04] !border-white/10">
                  <Statistic title="Orders · PAID_OFFLINE" value={data.counts.paidOfflineOrders} />
                </Card>
              </Col>
              <Col xs={24} sm={12} md={8} lg={8}>
                <Card size="small" className="!bg-white/[0.04] !border-white/10">
                  <Statistic title="Open fulfillment tasks" value={data.counts.openFulfillmentTasks} />
                </Card>
              </Col>
              <Col xs={24} sm={12} md={8} lg={8}>
                <Card size="small" className="!bg-white/[0.04] !border-white/10">
                  <Statistic title="Pending expert reviews" value={data.counts.pendingExpertReviews} />
                </Card>
              </Col>
              <Col xs={24} sm={12} md={8} lg={8}>
                <Card size="small" className="!bg-white/[0.04] !border-white/10">
                  <Statistic title="READY delivery artifacts" value={data.counts.readyDeliveryArtifacts} />
                </Card>
              </Col>
            </Row>

            <Typography.Title level={5} className="!text-white/90 !mb-3">
              Recent premium orders
            </Typography.Title>
            <Table
              size="small"
              pagination={false}
              rowKey="id"
              dataSource={data.queues.recentOrders as { id: string }[]}
              columns={[
                {
                  title: "ID",
                  dataIndex: "id",
                  key: "id",
                  ellipsis: true,
                  render: (id: string) => (
                    <Link href="/dashboard/premium-orders" className="text-indigo-300">
                      {id}
                    </Link>
                  ),
                },
                { title: "Status", dataIndex: "status", key: "status", width: 120, render: (s: string) => <Tag>{s}</Tag> },
                { title: "Package", dataIndex: "packageKey", key: "packageKey", width: 140 },
                { title: "Email", dataIndex: "email", key: "email", ellipsis: true },
              ]}
              className="mb-8"
            />

            <Typography.Title level={5} className="!text-white/90 !mb-3">
              Open fulfillment tasks (urgent first)
            </Typography.Title>
            <Table
              size="small"
              pagination={false}
              rowKey="id"
              dataSource={data.queues.urgentTasks as { id: string }[]}
              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: "Priority",
                  dataIndex: "priority",
                  key: "priority",
                  width: 90,
                  render: (p: string) => <Tag color={p === "HIGH" ? "red" : "blue"}>{p}</Tag>,
                },
                { title: "Status", dataIndex: "status", key: "status", width: 130 },
                { title: "Due", dataIndex: "dueAt", key: "dueAt", width: 160, render: (d: string | null) => d ?? "—" },
              ]}
              className="mb-8"
            />

            <Typography.Title level={5} className="!text-white/90 !mb-3">
              Pending expert reviews
            </Typography.Title>
            <Table
              size="small"
              pagination={false}
              rowKey="id"
              dataSource={data.queues.pendingReviews as { id: string }[]}
              columns={[
                {
                  title: "Review",
                  dataIndex: "id",
                  key: "id",
                  ellipsis: true,
                  render: (id: string) => (
                    <Link href={`/dashboard/expert-reviews/${id}`} className="text-indigo-300">
                      {id}
                    </Link>
                  ),
                },
                { title: "Reading title", dataIndex: "savedReadingTitle", key: "savedReadingTitle", ellipsis: true },
                { title: "Status", dataIndex: "status", key: "status", width: 120 },
              ]}
              className="mb-8"
            />

            <Typography.Title level={5} className="!text-white/90 !mb-3">
              Ready delivery artifacts
            </Typography.Title>
            <Table
              size="small"
              pagination={false}
              rowKey="id"
              dataSource={data.queues.readyDeliveries as { id: string }[]}
              columns={[
                { title: "Title", dataIndex: "title", key: "title", ellipsis: true },
                { title: "Order", dataIndex: "orderId", key: "orderId", ellipsis: true },
                { title: "Type", dataIndex: "type", key: "type", width: 100 },
                { title: "Updated", dataIndex: "updatedAt", key: "updatedAt", width: 180 },
              ]}
            />
          </>
        ) : null}
      </Card>
    </div>
  );
}
