"use client";

import Link from "next/link";
import { useParams } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { ArrowLeft, Loader2, Settings2 } from "lucide-react";
import { TopicScanResults, type Scan } from "@/components/inspiration/topic-scan-results";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/layout/page-header";
import { notify } from "@/lib/notifications/store";
import { TOPIC_GOAL_LABELS, isPlacementGoal } from "@/lib/types/topic-goal";
import { parseFetchJson } from "@/lib/utils";

interface Topic {
  id: string;
  label: string;
  query: string;
  topicGoal: string;
}

export default function TopicScanResultsPage() {
  const params = useParams();
  const topicId = params.topicId as string;

  const [topic, setTopic] = useState<Topic | null>(null);
  const [scans, setScans] = useState<Scan[]>([]);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    try {
      const [topicsRes, scansRes] = await Promise.all([
        fetch("/api/topics"),
        fetch(`/api/scans?topicId=${topicId}`),
      ]);
      const topicsData = await parseFetchJson<{ topics?: Topic[]; error?: string }>(topicsRes);
      const scansData = await parseFetchJson<{ scans?: Scan[]; error?: string }>(scansRes);

      if (!topicsRes.ok) {
        notify({ type: "error", title: "載入主題失敗", message: topicsData.error });
      }
      if (!scansRes.ok) {
        notify({ type: "error", title: "載入海巡失敗", message: scansData.error });
      }

      const found = (topicsData.topics ?? []).find((t) => t.id === topicId) ?? null;
      setTopic(found);
      setScans(scansData.scans ?? []);
    } catch (err) {
      const message = err instanceof Error ? err.message : "載入失敗";
      notify({ type: "error", title: "載入海巡成果失敗", message });
      setTopic(null);
      setScans([]);
    } finally {
      setLoading(false);
    }
  }, [topicId]);

  useEffect(() => {
    setLoading(true);
    load();
  }, [load]);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (!topic) {
    return (
      <div className="py-16 text-center">
        <p className="text-muted-foreground">找不到主題</p>
        <Button size="sm" variant="outline" className="mt-4" asChild>
          <Link href="/scans">返回找靈感</Link>
        </Button>
      </div>
    );
  }

  const goal = isPlacementGoal(topic.topicGoal) ? "placement" : "viral";

  return (
    <div>
      <div className="mb-4">
        <Button variant="ghost" size="sm" asChild>
          <Link href={`/scans?mode=${goal}`}>
            <ArrowLeft className="h-4 w-4" />
            返回主題列表
          </Link>
        </Button>
      </div>

      <PageHeader
        title={topic.label}
        description={`${topic.query} · ${TOPIC_GOAL_LABELS[goal]} · 海巡成果`}
        action={
          <Button size="sm" variant="outline" asChild>
            <Link href={`/scans/${topicId}`}>
              <Settings2 className="h-3.5 w-3.5" />
              設定主題
            </Link>
          </Button>
        }
      />

      <TopicScanResults
        scans={scans}
        onReload={load}
        emptyAction={
          <Button size="sm" asChild>
            <Link href={`/scans/${topicId}`}>前往設定並海巡</Link>
          </Button>
        }
      />
    </div>
  );
}