"use client";

import { useEffect, useState, useCallback } from "react";
import { useSession } from "next-auth/react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { api } from "@/lib/api";
import { SuggestionList } from "@/components/dashboard/SuggestionCard";
import type {
  Suggestion,
  SuggestionListResponse,
  SuggestionStatus,
} from "@/types/suggestion";
import {
  RefreshCw,
  Loader2,
  Filter,
  Lightbulb,
} from "lucide-react";

// 建议类型筛选选项
const TYPE_OPTIONS: { value: string; label: string }[] = [
  { value: "all", label: "全部类型" },
  { value: "content_optimization", label: "内容优化" },
  { value: "platform_targeting", label: "平台定向" },
  { value: "competitor_gap", label: "竞品差距" },
  { value: "query_expansion", label: "查询词扩展" },
  { value: "citation_improvement", label: "引用改善" },
];

// 优先级筛选选项
const PRIORITY_OPTIONS: { value: string; label: string }[] = [
  { value: "all", label: "全部优先级" },
  { value: "high", label: "高优先级" },
  { value: "medium", label: "中优先级" },
  { value: "low", label: "低优先级" },
];

// 状态筛选选项
const STATUS_OPTIONS: { value: string; label: string }[] = [
  { value: "all", label: "全部状态" },
  { value: "pending", label: "待处理" },
  { value: "in_progress", label: "进行中" },
  { value: "completed", label: "已完成" },
  { value: "dismissed", label: "已忽略" },
];

// 进度统计
interface ProgressStats {
  total: number;
  pending: number;
  in_progress: number;
  completed: number;
  dismissed: number;
}

export default function SuggestionsPage() {
  const { data: session } = useSession();
  const [suggestions, setSuggestions] = useState<Suggestion[]>([]);
  const [loading, setLoading] = useState(true);
  const [regenerating, setRegenerating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [brandId, setBrandId] = useState<string>("");

  // 筛选条件
  const [typeFilter, setTypeFilter] = useState("all");
  const [priorityFilter, setPriorityFilter] = useState("all");
  const [statusFilter, setStatusFilter] = useState("all");

  // 获取品牌ID
  useEffect(() => {
    const token = session?.accessToken;
    if (!token) return;

    async function loadBrandId() {
      try {
        const brandsData = await api.brands.list(token!, { limit: 1 });
        const brands = brandsData as { items?: { id: string }[] };
        if (brands.items && brands.items.length > 0) {
          setBrandId(brands.items[0].id);
        }
      } catch (err) {
        console.error("获取品牌失败:", err);
      }
    }

    loadBrandId();
  }, [session?.accessToken]);

  // 加载建议
  const loadSuggestions = useCallback(async () => {
    const token = session?.accessToken;
    if (!token || !brandId) return;

    try {
      setLoading(true);
      setError(null);
      const params: Record<string, string | number> = {};
      if (typeFilter !== "all") params.type = typeFilter;
      if (priorityFilter !== "all") params.priority = priorityFilter;
      if (statusFilter !== "all") params.status = statusFilter;

      const data = (await api.suggestions.getSuggestions(
        token,
        brandId,
        params,
      )) as SuggestionListResponse;
      setSuggestions(data.suggestions || []);
    } catch (err) {
      console.error("加载建议失败:", err);
      setError(err instanceof Error ? err.message : "加载建议失败");
    } finally {
      setLoading(false);
    }
  }, [session?.accessToken, brandId, typeFilter, priorityFilter, statusFilter]);

  useEffect(() => {
    loadSuggestions();
  }, [loadSuggestions]);

  // 重新生成建议
  const handleRegenerate = async () => {
    const token = session?.accessToken;
    if (!token || !brandId) return;

    try {
      setRegenerating(true);
      const data = (await api.suggestions.regenerateSuggestions(
        token,
        brandId,
      )) as SuggestionListResponse;
      setSuggestions(data.suggestions || []);
    } catch (err) {
      console.error("重新生成建议失败:", err);
      setError(err instanceof Error ? err.message : "重新生成建议失败");
    } finally {
      setRegenerating(false);
    }
  };

  // 更新建议状态
  const handleStatusChange = async (suggestionId: string, newStatus: string) => {
    const token = session?.accessToken;
    if (!token || !brandId) return;

    try {
      await api.suggestions.updateSuggestionStatus(
        token,
        brandId,
        suggestionId,
        newStatus,
      );
      // 更新本地状态
      setSuggestions((prev) =>
        prev.map((s) =>
          s.id === suggestionId ? { ...s, status: newStatus as SuggestionStatus } : s,
        ),
      );
    } catch (err) {
      console.error("更新建议状态失败:", err);
    }
  };

  // 计算进度统计
  const progressStats: ProgressStats = suggestions.reduce(
    (acc, s) => {
      acc.total++;
      acc[s.status as keyof ProgressStats] =
        (acc[s.status as keyof ProgressStats] || 0) + 1;
      return acc;
    },
    { total: 0, pending: 0, in_progress: 0, completed: 0, dismissed: 0 },
  );

  const completionRate =
    progressStats.total > 0
      ? Math.round(
          ((progressStats.completed + progressStats.dismissed) /
            progressStats.total) *
            100,
        )
      : 0;

  // 加载骨架屏
  if (loading && suggestions.length === 0) {
    return (
      <div className="space-y-6">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">优化建议</h2>
          <p className="text-muted-foreground">
            基于品牌数据的可操作优化建议
          </p>
        </div>
        <div className="grid gap-4 md:grid-cols-4">
          {[1, 2, 3, 4].map((i) => (
            <Card key={i}>
              <CardContent className="p-6">
                <Skeleton className="h-4 w-20 mb-2" />
                <Skeleton className="h-8 w-12" />
              </CardContent>
            </Card>
          ))}
        </div>
        <Card>
          <CardContent className="p-6 space-y-3">
            {[1, 2, 3, 4, 5].map((i) => (
              <Skeleton key={i} className="h-28 w-full" />
            ))}
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">优化建议</h2>
          <p className="text-muted-foreground">
            基于品牌数据的可操作优化建议，帮助您提升在AI平台的可见性
          </p>
        </div>
        <Button
          onClick={handleRegenerate}
          disabled={regenerating || !brandId}
          variant="outline"
        >
          {regenerating ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              生成中...
            </>
          ) : (
            <>
              <RefreshCw className="mr-2 h-4 w-4" />
              重新生成
            </>
          )}
        </Button>
      </div>

      {/* 进度统计卡片 */}
      <div className="grid gap-4 md:grid-cols-5">
        <Card>
          <CardContent className="p-4">
            <div className="text-sm text-muted-foreground">总建议</div>
            <div className="text-2xl font-bold">{progressStats.total}</div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="text-sm text-muted-foreground">待处理</div>
            <div className="text-2xl font-bold text-gray-600">
              {progressStats.pending}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="text-sm text-muted-foreground">进行中</div>
            <div className="text-2xl font-bold text-blue-600">
              {progressStats.in_progress}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="text-sm text-muted-foreground">已完成</div>
            <div className="text-2xl font-bold text-emerald-600">
              {progressStats.completed}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="text-sm text-muted-foreground">完成率</div>
            <div className="text-2xl font-bold">{completionRate}%</div>
            <div className="mt-1 h-2 w-full overflow-hidden rounded-full bg-gray-100">
              <div
                className="h-full rounded-full bg-emerald-500 transition-all"
                style={{ width: `${completionRate}%` }}
              />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 筛选栏 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-4 flex-wrap">
            <div className="flex items-center gap-2">
              <Filter className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm font-medium">筛选:</span>
            </div>
            <Select value={typeFilter} onValueChange={setTypeFilter}>
              <SelectTrigger className="w-[140px] h-8 text-xs">
                <SelectValue placeholder="类型" />
              </SelectTrigger>
              <SelectContent>
                {TYPE_OPTIONS.map((opt) => (
                  <SelectItem key={opt.value} value={opt.value}>
                    {opt.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={priorityFilter} onValueChange={setPriorityFilter}>
              <SelectTrigger className="w-[140px] h-8 text-xs">
                <SelectValue placeholder="优先级" />
              </SelectTrigger>
              <SelectContent>
                {PRIORITY_OPTIONS.map((opt) => (
                  <SelectItem key={opt.value} value={opt.value}>
                    {opt.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-[140px] h-8 text-xs">
                <SelectValue placeholder="状态" />
              </SelectTrigger>
              <SelectContent>
                {STATUS_OPTIONS.map((opt) => (
                  <SelectItem key={opt.value} value={opt.value}>
                    {opt.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* 错误状态 */}
      {error && (
        <div className="rounded-lg border border-red-200 bg-red-50 p-4 text-red-600">
          <p>{error}</p>
          <button
            onClick={loadSuggestions}
            className="mt-2 text-sm underline hover:no-underline"
          >
            重试
          </button>
        </div>
      )}

      {/* 建议列表 */}
      {!brandId ? (
        <Card>
          <CardContent className="flex h-[200px] flex-col items-center justify-center text-muted-foreground">
            <Lightbulb className="mb-2 h-8 w-8" />
            <p>请先创建品牌以获取优化建议</p>
          </CardContent>
        </Card>
      ) : (
        <SuggestionList
          suggestions={suggestions}
          brandId={brandId}
          onStatusChange={handleStatusChange}
          loading={loading}
          onRegenerate={handleRegenerate}
        />
      )}
    </div>
  );
}
