"use client";

import { useState, useMemo } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  CheckCircle,
  AlertCircle,
  XCircle,
  HelpCircle,
  Search,
  FileText,
  Link,
  Shield,
  BarChart3,
  Zap,
  ArrowRight,
  RefreshCw,
} from "lucide-react";
import { useApi } from "@/lib/hooks/use-api";
import { diagnosisApi } from "@/lib/api/diagnosis";
import type {
  DiagnosisTab,
  DiagnosisDimension,
  DiagnosisResult,
  CombinedDiagnosisResponse,
} from "@/types/diagnosis";
import type { BrandListResponse } from "@/types/brand";

function getStatusIcon(status: "pass" | "warning" | "fail") {
  switch (status) {
    case "pass":
      return <CheckCircle className="h-4 w-4 text-emerald-500" />;
    case "warning":
      return <AlertCircle className="h-4 w-4 text-amber-500" />;
    case "fail":
      return <XCircle className="h-4 w-4 text-red-500" />;
  }
}

function getStatusBadge(status: "pass" | "warning" | "fail") {
  const config = {
    pass: { label: "通过", variant: "default" as const, className: "bg-emerald-100 text-emerald-700 hover:bg-emerald-100" },
    warning: { label: "警告", variant: "secondary" as const, className: "bg-amber-100 text-amber-700 hover:bg-amber-100" },
    fail: { label: "未通过", variant: "destructive" as const, className: "bg-red-100 text-red-700 hover:bg-red-100" },
  };
  const c = config[status];
  return <Badge className={c.className}>{c.label}</Badge>;
}

function DimensionCard({ dimension }: { dimension: DiagnosisDimension }) {
  const [expanded, setExpanded] = useState(false);
  const scorePercentage = (dimension.score / dimension.max_score) * 100;
  const barColor =
    dimension.status === "pass"
      ? "bg-emerald-500"
      : dimension.status === "warning"
      ? "bg-amber-500"
      : "bg-red-500";

  return (
    <Card className="mb-4">
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <CardTitle className="text-lg">{dimension.name}</CardTitle>
            {getStatusBadge(dimension.status as "pass" | "warning" | "fail")}
          </div>
          <div className="text-right">
            <span className="text-2xl font-bold">{dimension.score}</span>
            <span className="text-sm text-muted-foreground">/{dimension.max_score}</span>
          </div>
        </div>
        <div className="mt-2 h-2 w-full overflow-hidden rounded-full bg-gray-100">
          <div
            className={`h-full rounded-full transition-all ${barColor}`}
            style={{ width: `${scorePercentage}%` }}
          />
        </div>
      </CardHeader>
      <CardContent>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setExpanded(!expanded)}
          className="w-full justify-between"
        >
          <span className="text-sm text-muted-foreground">
            {expanded ? "收起详情" : `查看${dimension.items.length}个诊断项`}
          </span>
          <ArrowRight className={`h-4 w-4 transition-transform ${expanded ? "rotate-90" : ""}`} />
        </Button>
        {expanded && (
          <div className="mt-4 space-y-3">
            {dimension.items.map((item) => (
              <div key={item.name} className="flex items-start gap-3 rounded-lg border p-3">
                {getStatusIcon(item.status as "pass" | "warning" | "fail")}
                <div className="flex-1">
                  <p className="text-sm font-medium">{item.name}</p>
                  <p className="text-xs text-muted-foreground">{item.description}</p>
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
}

function SummaryCard({ title, score, icon }: { title: string; score: number; icon: React.ReactNode }) {
  const status = score >= 80 ? "pass" : score >= 60 ? "warning" : "fail";
  const statusColor =
    status === "pass" ? "text-emerald-600" : status === "warning" ? "text-amber-600" : "text-red-600";

  return (
    <Card>
      <CardContent className="pt-6">
        <div className="flex items-center gap-3">
          <div className={`rounded-lg bg-gray-100 p-2 ${statusColor}`}>{icon}</div>
          <div>
            <p className="text-sm text-muted-foreground">{title}</p>
            <p className={`text-2xl font-bold ${statusColor}`}>{score}</p>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

function LoadingState() {
  return (
    <div className="flex flex-col items-center justify-center py-12">
      <RefreshCw className="h-8 w-8 animate-spin text-muted-foreground" />
      <p className="mt-4 text-sm text-muted-foreground">正在加载诊断数据...</p>
    </div>
  );
}

function ErrorState({ message, onRetry }: { message: string; onRetry: () => void }) {
  return (
    <Card className="border-red-200">
      <CardContent className="pt-6">
        <div className="flex flex-col items-center gap-3 text-center">
          <XCircle className="h-10 w-10 text-red-500" />
          <div>
            <p className="font-medium text-red-800">加载诊断数据失败</p>
            <p className="text-sm text-red-600">{message}</p>
          </div>
          <Button variant="outline" size="sm" onClick={onRetry}>
            <RefreshCw className="mr-2 h-4 w-4" />
            重试
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}

function EmptyState() {
  return (
    <Card>
      <CardContent className="pt-6">
        <div className="flex flex-col items-center gap-3 text-center">
          <HelpCircle className="h-10 w-10 text-muted-foreground" />
          <div>
            <p className="font-medium">暂无品牌数据</p>
            <p className="text-sm text-muted-foreground">请先创建品牌，然后进行诊断分析</p>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

function getPriorityColor(priority: string) {
  switch (priority.toLowerCase()) {
    case "high":
    case "紧急":
      return { border: "border-red-200", bg: "bg-red-50", text: "text-red-800", subtext: "text-red-600", icon: "text-red-500" };
    case "medium":
    case "中":
      return { border: "border-amber-200", bg: "bg-amber-50", text: "text-amber-800", subtext: "text-amber-600", icon: "text-amber-500" };
    default:
      return { border: "border-blue-200", bg: "bg-blue-50", text: "text-blue-800", subtext: "text-blue-600", icon: "text-blue-500" };
  }
}

export default function DiagnosisPage() {
  const [activeTab, setActiveTab] = useState<DiagnosisTab>("combined");

  const { data: brandsData, isLoading: brandsLoading, refresh: refreshBrands } = useApi<BrandListResponse>(
    "/api/v1/brands/?limit=1&offset=0"
  );

  const selectedBrand = brandsData?.items?.[0];
  const brandId = selectedBrand?.id ?? null;

  const {
    data: seoData,
    isLoading: seoLoading,
    error: seoError,
    refresh: refreshSeo,
  } = useApi<DiagnosisResult>(
    brandId ? `/api/v1/diagnosis/seo/${brandId}` : null
  );

  const {
    data: geoData,
    isLoading: geoLoading,
    error: geoError,
    refresh: refreshGeo,
  } = useApi<DiagnosisResult>(
    brandId ? `/api/v1/diagnosis/geo/${brandId}` : null
  );

  const {
    data: combinedData,
    isLoading: combinedLoading,
    error: combinedError,
    refresh: refreshCombined,
  } = useApi<CombinedDiagnosisResponse>(
    brandId ? `/api/v1/diagnosis/combined/${brandId}` : null
  );

  const isLoading = brandsLoading || seoLoading || geoLoading || combinedLoading;

  const handleRefreshAll = () => {
    refreshBrands();
    refreshSeo();
    refreshGeo();
    refreshCombined();
  };

  const seoDimensions = useMemo(
    () => (activeTab === "seo" ? seoData?.dimensions ?? [] : combinedData?.seo_dimensions ?? []),
    [activeTab, seoData, combinedData]
  );

  const geoDimensions = useMemo(
    () => (activeTab === "geo" ? geoData?.dimensions ?? [] : combinedData?.geo_dimensions ?? []),
    [activeTab, geoData, combinedData]
  );

  const seoOverallScore = useMemo(() => {
    if (seoData?.overall_score != null) return seoData.overall_score;
    if (combinedData?.seo_score != null) return combinedData.seo_score;
    if (seoDimensions.length === 0) return 0;
    return Math.round(
      seoDimensions.reduce((sum, d) => sum + d.score, 0) / seoDimensions.length
    );
  }, [seoData, combinedData, seoDimensions]);

  const geoOverallScore = useMemo(() => {
    if (geoData?.overall_score != null) return geoData.overall_score;
    if (combinedData?.geo_score != null) return combinedData.geo_score;
    if (geoDimensions.length === 0) return 0;
    return Math.round(
      geoDimensions.reduce((sum, d) => sum + d.score, 0) / geoDimensions.length
    );
  }, [geoData, combinedData, geoDimensions]);

  const combinedScore = useMemo(() => {
    if (combinedData?.overall_score != null) return combinedData.overall_score;
    if (seoOverallScore && geoOverallScore) {
      return Math.round((seoOverallScore + geoOverallScore) / 2);
    }
    return 0;
  }, [combinedData, seoOverallScore, geoOverallScore]);

  const recommendations = useMemo(
    () => combinedData?.recommendations ?? seoData?.recommendations ?? geoData?.recommendations ?? [],
    [combinedData, seoData, geoData]
  );

  const currentError = seoError || geoError || combinedError;

  if (!brandsLoading && !selectedBrand) {
    return (
      <div className="space-y-6">
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <h1 className="text-2xl font-bold tracking-tight">诊断分析</h1>
            <p className="text-muted-foreground">
              全面评估品牌在搜索引擎和AI生成式引擎中的可见性
            </p>
          </div>
        </div>
        <EmptyState />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">诊断分析</h1>
          <p className="text-muted-foreground">
            全面评估品牌在搜索引擎和AI生成式引擎中的可见性
          </p>
          {selectedBrand && (
            <p className="text-sm text-muted-foreground mt-1">
              当前品牌: {selectedBrand.name}
            </p>
          )}
        </div>
        <Button variant="outline" onClick={handleRefreshAll} disabled={isLoading}>
          <RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
          重新诊断
        </Button>
      </div>

      {isLoading ? (
        <LoadingState />
      ) : currentError ? (
        <ErrorState message={currentError.message} onRetry={handleRefreshAll} />
      ) : (
        <>
          {/* Summary Cards */}
          <div className="grid gap-4 md:grid-cols-3">
            <SummaryCard
              title="综合评分"
              score={combinedScore}
              icon={<BarChart3 className="h-5 w-5" />}
            />
            <SummaryCard
              title="SEO诊断评分"
              score={seoOverallScore}
              icon={<Search className="h-5 w-5" />}
            />
            <SummaryCard
              title="GEO诊断评分"
              score={geoOverallScore}
              icon={<Zap className="h-5 w-5" />}
            />
          </div>

          {/* Tabs */}
          <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as DiagnosisTab)}>
            <TabsList className="grid w-full grid-cols-3">
              <TabsTrigger value="combined">综合诊断</TabsTrigger>
              <TabsTrigger value="seo">SEO诊断</TabsTrigger>
              <TabsTrigger value="geo">GEO诊断</TabsTrigger>
            </TabsList>

            {/* Combined Tab */}
            <TabsContent value="combined" className="space-y-6">
              <div className="grid gap-6 md:grid-cols-2">
                <div>
                  <h2 className="mb-4 text-lg font-semibold flex items-center gap-2">
                    <Search className="h-5 w-5 text-blue-500" />
                    SEO诊断概览
                  </h2>
                  {seoDimensions.length > 0 ? (
                    seoDimensions.map((dim) => (
                      <div key={dim.name} className="mb-3 flex items-center justify-between rounded-lg border p-3">
                        <div className="flex items-center gap-2">
                          {getStatusIcon(dim.status as "pass" | "warning" | "fail")}
                          <span className="text-sm font-medium">{dim.name}</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <span className="text-sm font-bold">{dim.score}</span>
                          <span className="text-xs text-muted-foreground">/{dim.max_score}</span>
                        </div>
                      </div>
                    ))
                  ) : (
                    <p className="text-sm text-muted-foreground">暂无SEO诊断数据</p>
                  )}
                </div>
                <div>
                  <h2 className="mb-4 text-lg font-semibold flex items-center gap-2">
                    <Zap className="h-5 w-5 text-purple-500" />
                    GEO诊断概览
                  </h2>
                  {geoDimensions.length > 0 ? (
                    geoDimensions.map((dim) => (
                      <div key={dim.name} className="mb-3 flex items-center justify-between rounded-lg border p-3">
                        <div className="flex items-center gap-2">
                          {getStatusIcon(dim.status as "pass" | "warning" | "fail")}
                          <span className="text-sm font-medium">{dim.name}</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <span className="text-sm font-bold">{dim.score}</span>
                          <span className="text-xs text-muted-foreground">/{dim.max_score}</span>
                        </div>
                      </div>
                    ))
                  ) : (
                    <p className="text-sm text-muted-foreground">暂无GEO诊断数据</p>
                  )}
                </div>
              </div>

              {/* Priority Recommendations */}
              {recommendations.length > 0 && (
                <Card>
                  <CardHeader>
                    <CardTitle>优先优化建议</CardTitle>
                    <CardDescription>基于诊断结果，建议优先处理以下问题</CardDescription>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {recommendations.map((rec, index) => {
                      const colors = getPriorityColor(rec.priority);
                      return (
                        <div key={index} className={`rounded-lg border ${colors.border} ${colors.bg} p-4`}>
                          <div className="flex items-start gap-3">
                            {rec.priority.toLowerCase() === "high" || rec.priority.toLowerCase() === "紧急" ? (
                              <XCircle className={`mt-0.5 h-5 w-5 ${colors.icon}`} />
                            ) : (
                              <AlertCircle className={`mt-0.5 h-5 w-5 ${colors.icon}`} />
                            )}
                            <div>
                              <p className={`font-medium ${colors.text}`}>{rec.title}</p>
                              <p className={`text-sm ${colors.subtext}`}>{rec.description}</p>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </CardContent>
                </Card>
              )}
            </TabsContent>

            {/* SEO Tab */}
            <TabsContent value="seo" className="space-y-4">
              <Card className="mb-4">
                <CardHeader>
                  <CardTitle>SEO诊断详情</CardTitle>
                  <CardDescription>
                    从技术SEO、页面SEO、内容质量、外链分析、用户体验等维度全面评估
                  </CardDescription>
                </CardHeader>
              </Card>
              {seoDimensions.length > 0 ? (
                seoDimensions.map((dim) => (
                  <DimensionCard key={dim.name} dimension={dim} />
                ))
              ) : (
                <p className="text-sm text-muted-foreground text-center py-8">暂无SEO诊断数据</p>
              )}
            </TabsContent>

            {/* GEO Tab */}
            <TabsContent value="geo" className="space-y-4">
              <Card className="mb-4">
                <CardHeader>
                  <CardTitle>GEO诊断详情</CardTitle>
                  <CardDescription>
                    从内容可提取性、实体清晰度、E-E-A-T信号、Schema标记、主题权威、引用就绪度等维度评估
                  </CardDescription>
                </CardHeader>
              </Card>
              {geoDimensions.length > 0 ? (
                geoDimensions.map((dim) => (
                  <DimensionCard key={dim.name} dimension={dim} />
                ))
              ) : (
                <p className="text-sm text-muted-foreground text-center py-8">暂无GEO诊断数据</p>
              )}
            </TabsContent>
          </Tabs>
        </>
      )}
    </div>
  );
}
