"use client";

import { useEffect, useRef, useState } from "react";
import { useSession } from "next-auth/react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { api } from "@/lib/api";
import { PLATFORM_MAP } from "@/lib/platforms";
import { Check, X, Loader2, Quote, Filter } from "lucide-react";

interface CitationItem {
  id: string;
  query_id: string;
  platform: string;
  cited: boolean;
  citation_position: number | null;
  citation_text: string | null;
  competitor_brands: string[];
  queried_at: string;
}

interface QueryOption {
  id: string;
  keyword: string;
}

export default function CitationsPage() {
  const { data: session } = useSession();
  const [citations, setCitations] = useState<CitationItem[]>([]);
  const [queries, setQueries] = useState<QueryOption[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [selectedQuery, setSelectedQuery] = useState<string>("all");
  const [selectedPlatform, setSelectedPlatform] = useState<string>("all");
  const [startDate, setStartDate] = useState<string>("");
  const [endDate, setEndDate] = useState<string>("");
  const isFirstFilterEffect = useRef(true);

  useEffect(() => {
    if (!session?.accessToken) return;
    loadQueries();
    loadCitations();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [session?.accessToken]);

  useEffect(() => {
    if (!session?.accessToken) return;
    if (isFirstFilterEffect.current) {
      isFirstFilterEffect.current = false;
      return;
    }
    loadCitations();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedQuery, selectedPlatform, startDate, endDate, session?.accessToken]);

  async function loadQueries() {
    try {
      const data = await api.queries.list(session!.accessToken);
      setQueries(data.items || []);
    } catch {
      // 静默失败，查询词筛选为非必需
    }
  }

  async function loadCitations() {
    if (!session?.accessToken) return;
    try {
      setLoading(true);
      const params = new URLSearchParams();
      if (selectedQuery && selectedQuery !== "all") params.append("query_id", selectedQuery);
      if (selectedPlatform && selectedPlatform !== "all") params.append("platform", selectedPlatform);
      if (startDate) params.append("start_date", startDate);
      if (endDate) params.append("end_date", endDate);

      const data = await api.citations.list(
        session.accessToken,
        params.toString()
      );
      setCitations(data.items || []);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "加载引用记录失败");
    } finally {
      setLoading(false);
    }
  }

  function handleFilter() {
    loadCitations();
  }

  function handleReset() {
    setSelectedQuery("all");
    setSelectedPlatform("all");
    setStartDate("");
    setEndDate("");
  }

  if (loading && citations.length === 0) {
    return (
      <div className="space-y-4">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">引用记录</h2>
          <p className="text-muted-foreground">查看各平台的引用检测结果</p>
        </div>
        <div className="flex h-[60vh] items-center justify-center">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div>
        <h2 className="text-2xl font-bold tracking-tight">引用记录</h2>
        <p className="text-muted-foreground">查看各平台的引用检测结果</p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-base">
            <Filter className="h-4 w-4" />
            筛选条件
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
            <div className="space-y-2">
              <Label htmlFor="query-filter">查询词</Label>
              <Select value={selectedQuery} onValueChange={setSelectedQuery}>
                <SelectTrigger id="query-filter">
                  <SelectValue placeholder="全部查询词" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部查询词</SelectItem>
                  {queries.map((q) => (
                    <SelectItem key={q.id} value={q.id}>
                      {q.keyword}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label htmlFor="platform-filter">平台</Label>
              <Select value={selectedPlatform} onValueChange={setSelectedPlatform}>
                <SelectTrigger id="platform-filter">
                  <SelectValue placeholder="全部平台" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部平台</SelectItem>
                  {Object.entries(PLATFORM_MAP).map(([key, label]) => (
                    <SelectItem key={key} value={key}>
                      {label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label htmlFor="start-date">开始日期</Label>
              <Input
                id="start-date"
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="end-date">结束日期</Label>
              <Input
                id="end-date"
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
              />
            </div>
            <div className="flex items-end gap-2">
              <Button onClick={handleFilter} className="flex-1">
                筛选
              </Button>
              <Button variant="outline" onClick={handleReset} className="flex-1">
                重置
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {error && (
        <div className="rounded-md bg-destructive/10 px-4 py-3 text-sm text-destructive">
          {error}
        </div>
      )}

      <Card>
        <CardHeader>
          <CardTitle className="text-base">引用记录列表</CardTitle>
        </CardHeader>
        <CardContent>
          {citations.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
              <Quote className="mb-4 h-12 w-12 opacity-20" />
              <p>暂无引用记录</p>
              <p className="text-sm">添加查询词并执行查询后将在此显示结果</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>平台</TableHead>
                    <TableHead>是否引用</TableHead>
                    <TableHead>引用位置</TableHead>
                    <TableHead>引用文本片段</TableHead>
                    <TableHead>竞争品牌</TableHead>
                    <TableHead>查询时间</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {citations.map((item) => (
                    <TableRow key={item.id}>
                      <TableCell className="font-medium">
                        {PLATFORM_MAP[item.platform] || item.platform}
                      </TableCell>
                      <TableCell>
                        {item.cited ? (
                          <div className="flex items-center gap-1 text-emerald-600">
                            <Check className="h-4 w-4" />
                            <span className="text-sm">已引用</span>
                          </div>
                        ) : (
                          <div className="flex items-center gap-1 text-red-500">
                            <X className="h-4 w-4" />
                            <span className="text-sm">未引用</span>
                          </div>
                        )}
                      </TableCell>
                      <TableCell>
                        {item.citation_position !== null
                          ? `第 ${item.citation_position} 位`
                          : "—"}
                      </TableCell>
                      <TableCell className="max-w-xs truncate">
                        {item.citation_text || "—"}
                      </TableCell>
                      <TableCell>
                        <div className="flex flex-wrap gap-1">
                          {item.competitor_brands?.length > 0 ? (
                            item.competitor_brands.map((brand) => (
                              <Badge key={brand} variant="secondary" className="text-xs">
                                {brand}
                              </Badge>
                            ))
                          ) : (
                            <span className="text-muted-foreground">—</span>
                          )}
                        </div>
                      </TableCell>
                      <TableCell className="text-muted-foreground">
                        {new Date(item.queried_at).toLocaleString("zh-CN")}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
