"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { Alert, Card, Descriptions, Spin, 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 Detail = {
  id: string;
  savedReadingId: string;
  reviewerUserId: string;
  status: string;
  summary: string | null;
  strategicNotes: string | null;
  timingNotes: string | null;
  correctionNotes: string | null;
  internalOnlyNotes: string | null;
  createdAt: string;
  updatedAt: string;
  linkage?: {
    archetype: { key: string; title?: string } | null;
    savedReading: { id: string; ownerUserId: string; title: string | null; createdAt: string };
    feedback: { totalCount: number; recent: unknown[] };
    premiumInterest: { totalCount: number; items: unknown[] };
  };
};

export default function ExpertReviewDetailPage() {
  const params = useParams();
  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) {
      setErr("Missing id.");
      setLoading(false);
      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/tu-vi-reviews/${encodeURIComponent(id)}`, {
      headers: { Authorization: `Bearer ${token}` },
    });
    if (res.status === 403) {
      setErr("MANAGER or SUPER_ADMIN required.");
      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]);

  const arch = row?.linkage?.archetype;

  return (
    <Card className="cms-surface-card" styles={{ body: { padding: "24px 28px" } }}>
      <CmsSectionTitle
        icon={<FileSearchOutlined />}
        title="Expert review"
        description="Internal-only fields stay off end-user saved-reading responses."
      />
      <div className="mb-4">
        <Link href="/dashboard/expert-reviews" className="text-sm text-indigo-300 hover:underline">
          ← All reviews
        </Link>
      </div>
      {err ? <Alert type="warning" message={err} showIcon className="mb-4" /> : null}
      {loading ? (
        <div className="py-16 text-center">
          <Spin />
        </div>
      ) : row ? (
        <>
          <Descriptions bordered size="small" column={1} className="mb-4">
            <Descriptions.Item label="Status">{row.status}</Descriptions.Item>
            <Descriptions.Item label="Saved reading">{row.savedReadingId}</Descriptions.Item>
            <Descriptions.Item label="Reviewer">{row.reviewerUserId}</Descriptions.Item>
            <Descriptions.Item label="Archetype (linkage)">
              {arch ? `${arch.key}${arch.title ? ` — ${arch.title}` : ""}` : "—"}
            </Descriptions.Item>
            <Descriptions.Item label="Feedback (linkage)">
              {row.linkage ? `${row.linkage.feedback.totalCount} total` : "—"}
            </Descriptions.Item>
            <Descriptions.Item label="Premium interest (linkage)">
              {row.linkage ? `${row.linkage.premiumInterest.totalCount} total` : "—"}
            </Descriptions.Item>
          </Descriptions>
          <Typography.Title level={5} className="!text-white/90">
            Public-eligible notes (subset also shown to user when REVIEWED)
          </Typography.Title>
          <div className="space-y-3 text-sm text-white/80">
            <p className="whitespace-pre-wrap">{row.summary ?? "—"}</p>
            <p className="whitespace-pre-wrap">{row.strategicNotes ?? "—"}</p>
            <p className="whitespace-pre-wrap">{row.timingNotes ?? "—"}</p>
          </div>
          <Typography.Title level={5} className="!mt-6 !text-amber-200/90">
            Internal / QA
          </Typography.Title>
          <div className="space-y-3 text-sm text-white/75">
            <p className="whitespace-pre-wrap">{row.correctionNotes ?? "—"}</p>
            <p className="whitespace-pre-wrap">{row.internalOnlyNotes ?? "—"}</p>
          </div>
        </>
      ) : null}
    </Card>
  );
}
