"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { Alert, Card, Spin, Table, Typography } from "antd";
import { FileSearchOutlined } from "@ant-design/icons";

import { CmsSectionTitle } from "@/components/admin/CmsSectionTitle";

const apiBase = () => process.env.NEXT_PUBLIC_API_BASE_URL ?? "";

type ReviewRow = {
  id: string;
  savedReadingId: string;
  reviewerUserId: string;
  status: string;
  summary: string | null;
  updatedAt: string;
};

export default function ExpertReviewsListPage() {
  const [items, setItems] = useState<ReviewRow[]>([]);
  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/tu-vi-reviews?limit=50`, {
      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?: ReviewRow[] };
    setItems(body.items ?? []);
    setLoading(false);
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  return (
    <Card className="cms-surface-card" styles={{ body: { padding: "24px 28px" } }}>
      <CmsSectionTitle
        icon={<FileSearchOutlined />}
        title="Tu Vi expert reviews"
        description="Internal workflow — link readings to human review notes. See docs/launch/human-expert-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: "Review",
              key: "id",
              render: (_, r) => (
                <Link className="text-indigo-300 hover:underline" href={`/dashboard/expert-reviews/${r.id}`}>
                  {r.id.slice(0, 10)}…
                </Link>
              ),
            },
            { title: "Saved reading", dataIndex: "savedReadingId", key: "savedReadingId" },
            { title: "Status", dataIndex: "status", key: "status", width: 120 },
            {
              title: "Summary",
              dataIndex: "summary",
              key: "summary",
              ellipsis: true,
              render: (v: string | null) => (v && v.trim() ? `${v.slice(0, 80)}${v.length > 80 ? "…" : ""}` : "—"),
            },
          ]}
        />
      )}
      <Typography.Paragraph className="!mt-4 !mb-0 text-xs text-white/45">
        Create reviews via API: POST /internal/tu-vi-reviews with JSON body{" "}
        <code className="text-[11px]">{`{"savedReadingId":"…"}`}</code>.
      </Typography.Paragraph>
    </Card>
  );
}
