"use client";

import { useEffect, useState, useCallback } from "react";
import { useSession } from "next-auth/react";
import { useParams, useRouter } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { BrandFormDialog } from "@/components/brand/BrandFormDialog";
import { api } from "@/lib/api";
import { PLATFORM_MAP } from "@/lib/platforms";
import type {
  BrandDetail,
  Competitor,
  CreateCompetitorRequest,
  CompetitorRecommendationItem,
  CompetitorRecommendationResponse,
} from "@/types/brand";
import {
  ArrowLeft,
  Star,
  Calendar,
  Globe,
  Building,
  Play,
  Plus,
  Trash2,
  Loader2,
  ExternalLink,
  Users,
  Lightbulb,
  Check,
  Sparkles,
} from "lucide-react";
import Link from "next/link";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NextActionCard } from "@/components/dashboard/NextActionCard";
import type { ActionContext } from "@/types/next-action";

export default function BrandDetailPage() {
  const params = useParams();
  const _router = useRouter();
  const { data: session } = useSession();
  const brandId = params.id as string;

  const [brand, setBrand] = useState<BrandDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [querying, setQuerying] = useState(false);

  // 竞品相关状态
  const [showAddCompetitor, setShowAddCompetitor] = useState(false);
  const [competitorName, setCompetitorName] = useState("");
  const [competitorAliases, setCompetitorAliases] = useState("");
  const [addingCompetitor, setAddingCompetitor] = useState(false);
  const [deleteCompetitor, setDeleteCompetitor] = useState<Competitor | null>(
    null,
  );
  const [deletingCompetitor, setDeletingCompetitor] = useState(false);

  // 推荐竞品相关状态
  const [recommendations, setRecommendations] = useState<
    CompetitorRecommendationItem[]
  >([]);
  const [loadingRecommendations, setLoadingRecommendations] = useState(false);
  const [showRecommendations, setShowRecommendations] = useState(false);

  const fetchBrandDetail = useCallback(async () => {
    const token = session?.accessToken;
    if (!token || !brandId) return;

    try {
      setLoading(true);
      const data = (await api.brands.getDetail(token, brandId)) as BrandDetail;
      setBrand(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : "加载品牌详情失败");
    } finally {
      setLoading(false);
    }
  }, [session?.accessToken, brandId]);

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

  const handleQueryNow = async () => {
    if (!session?.accessToken || !brand) return;

    try {
      setQuerying(true);
      await api.brands.queryNow(session.accessToken, brand.id);
      alert("查询任务已加入队列，请稍后刷新查看结果");
      fetchBrandDetail();
    } catch (err) {
      alert(err instanceof Error ? err.message : "查询失败");
    } finally {
      setQuerying(false);
    }
  };

  const handleAddCompetitor = async () => {
    if (!session?.accessToken || !brand || !competitorName.trim()) return;

    const aliasList = competitorAliases
      .split(",")
      .map((a) => a.trim())
      .filter((a) => a.length >= 2 && a.length <= 20);

    try {
      setAddingCompetitor(true);
      const data: CreateCompetitorRequest = {
        name: competitorName.trim(),
        aliases: aliasList.length > 0 ? aliasList : undefined,
      };
      await api.brands.addCompetitor(session.accessToken, brand.id, data);
      setShowAddCompetitor(false);
      setCompetitorName("");
      setCompetitorAliases("");
      fetchBrandDetail();
    } catch (err) {
      alert(err instanceof Error ? err.message : "添加竞品失败");
    } finally {
      setAddingCompetitor(false);
    }
  };

  const handleDeleteCompetitor = async () => {
    if (!deleteCompetitor || !session?.accessToken || !brand) return;

    try {
      setDeletingCompetitor(true);
      await api.brands.deleteCompetitor(
        session.accessToken,
        brand.id,
        deleteCompetitor.id,
      );
      setDeleteCompetitor(null);
      fetchBrandDetail();
    } catch (err) {
      alert(err instanceof Error ? err.message : "删除竞品失败");
    } finally {
      setDeletingCompetitor(false);
    }
  };

  const handleLoadRecommendations = async () => {
    if (!session?.accessToken || !brand) return;

    try {
      setLoadingRecommendations(true);
      setShowRecommendations(true);
      const data = (await api.brands.getCompetitorRecommendations(
        session.accessToken,
        brand.id,
      )) as CompetitorRecommendationResponse;
      setRecommendations(data.recommendations || []);
    } catch (err) {
      console.error("获取推荐竞品失败:", err);
      setRecommendations([]);
    } finally {
      setLoadingRecommendations(false);
    }
  };

  const handleAddRecommendedCompetitor = async (name: string) => {
    if (!session?.accessToken || !brand) return;

    try {
      const data: CreateCompetitorRequest = { name };
      await api.brands.addCompetitor(session.accessToken, brand.id, data);
      fetchBrandDetail();
      // 从推荐列表中移除已添加的
      setRecommendations((prev) => prev.filter((r) => r.name !== name));
    } catch (err) {
      alert(err instanceof Error ? err.message : "添加竞品失败");
    }
  };

  const formatDate = (dateString: string | null) => {
    if (!dateString) return "暂无";
    const date = new Date(dateString);
    return date.toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const getFrequencyLabel = (frequency: string) => {
    const labels: Record<string, string> = {
      daily: "每日",
      weekly: "每周",
      monthly: "每月",
    };
    return labels[frequency] || frequency;
  };

  const getIndustryLabel = (industry: string | null) => {
    if (!industry) return "未设置";
    const labels: Record<string, string> = {
      technology: "科技",
      finance: "金融",
      retail: "零售",
      healthcare: "医疗健康",
      education: "教育",
      manufacturing: "制造业",
      entertainment: "娱乐",
      travel: "旅游",
      food: "餐饮",
      automotive: "汽车",
      real_estate: "房地产",
      other: "其他",
    };
    return labels[industry] || industry;
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center gap-4">
          <Skeleton className="h-10 w-10" />
          <Skeleton className="h-8 w-48" />
        </div>
        <div className="grid gap-4 md:grid-cols-2">
          <Card>
            <CardHeader>
              <Skeleton className="h-6 w-32" />
            </CardHeader>
            <CardContent>
              <Skeleton className="h-20 w-full" />
            </CardContent>
          </Card>
          <Card>
            <CardHeader>
              <Skeleton className="h-6 w-32" />
            </CardHeader>
            <CardContent>
              <Skeleton className="h-20 w-full" />
            </CardContent>
          </Card>
        </div>
      </div>
    );
  }

  if (error || !brand) {
    return (
      <div className="flex h-[60vh] flex-col items-center justify-center gap-2">
        <p className="text-destructive">{error || "品牌不存在"}</p>
        <Link href="/brands">
          <Button variant="outline">返回品牌列表</Button>
        </Link>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 顶部导航 */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" asChild>
          <Link href="/brands">
            <ArrowLeft className="h-5 w-5" />
          </Link>
        </Button>
        <h2 className="text-2xl font-bold tracking-tight flex-1">
          {brand.name}
        </h2>
        <Button variant="outline" size="sm" asChild>
          <Link href="/brands">返回列表</Link>
        </Button>
        <BrandFormDialog
          editBrand={{
            id: brand.id,
            name: brand.name,
            aliases: brand.aliases,
            website: brand.website,
            industry: brand.industry,
            platforms: brand.platforms,
            frequency: brand.frequency,
          }}
          onSuccess={fetchBrandDetail}
          trigger={<Button variant="outline">编辑品牌</Button>}
        />
        <Button onClick={handleQueryNow} disabled={querying}>
          {querying && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
          <Play className="mr-2 h-4 w-4" />
          立即查询
        </Button>
      </div>

      {/* 基本信息卡片 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">基本信息</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
            {/* 综合评分 */}
            <div className="flex items-center gap-3">
              <div className="flex h-12 w-12 items-center justify-center rounded-full bg-amber-50">
                <Star className="h-6 w-6 text-amber-500" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">综合评分</p>
                <p className="text-2xl font-bold">
                  {brand.score?.overall ?? "-"}
                </p>
              </div>
            </div>

            {/* 查询频率 */}
            <div className="flex items-center gap-3">
              <div className="flex h-12 w-12 items-center justify-center rounded-full bg-blue-50">
                <Calendar className="h-6 w-6 text-blue-500" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">查询频率</p>
                <p className="text-lg font-semibold">
                  {getFrequencyLabel(brand.frequency)}
                </p>
              </div>
            </div>

            {/* 官方网站 */}
            <div className="flex items-center gap-3">
              <div className="flex h-12 w-12 items-center justify-center rounded-full bg-green-50">
                <Globe className="h-6 w-6 text-green-500" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">官方网站</p>
                {brand.website ? (
                  <a
                    href={brand.website}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-lg font-semibold text-primary hover:underline flex items-center gap-1"
                  >
                    访问
                    <ExternalLink className="h-3 w-3" />
                  </a>
                ) : (
                  <p className="text-lg font-semibold text-muted-foreground">
                    未设置
                  </p>
                )}
              </div>
            </div>

            {/* 所属行业 */}
            <div className="flex items-center gap-3">
              <div className="flex h-12 w-12 items-center justify-center rounded-full bg-purple-50">
                <Building className="h-6 w-6 text-purple-500" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">所属行业</p>
                <p className="text-lg font-semibold">
                  {getIndustryLabel(brand.industry)}
                </p>
              </div>
            </div>
          </div>

          {/* 品牌别名 */}
          {brand.aliases && brand.aliases.length > 0 && (
            <div className="mt-4 flex items-center gap-2">
              <span className="text-sm text-muted-foreground">别名:</span>
              <div className="flex flex-wrap gap-1">
                {brand.aliases.map((alias, index) => (
                  <Badge key={index} variant="secondary">
                    {alias}
                  </Badge>
                ))}
              </div>
            </div>
          )}

          {/* 时间信息 */}
          <div className="mt-4 flex gap-6 text-sm text-muted-foreground">
            <span>上次查询: {formatDate(brand.last_queried_at)}</span>
            <span>下次查询: {formatDate(brand.next_query_at)}</span>
          </div>
        </CardContent>
      </Card>

      {/* 平台评分 */}
      {brand.score &&
        Object.keys(brand.score).filter((k) => k !== "overall").length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle className="text-base">平台评分</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid gap-4 md:grid-cols-3 lg:grid-cols-5">
                {Object.entries(brand.score)
                  .filter(([key]) => key !== "overall")
                  .map(([platform, score]) => (
                    <div
                      key={platform}
                      className="flex items-center gap-3 rounded-lg border p-3"
                    >
                      <div className="flex-1">
                        <p className="text-sm text-muted-foreground">
                          {PLATFORM_MAP[platform] || platform}
                        </p>
                        <p className="text-xl font-bold">{score}</p>
                      </div>
                      <Star
                        className={`h-5 w-5 ${
                          (score as number) >= 70
                            ? "text-amber-500"
                            : (score as number) >= 50
                              ? "text-blue-500"
                              : "text-gray-400"
                        }`}
                        fill="currentColor"
                      />
                    </div>
                  ))}
              </div>
            </CardContent>
          </Card>
        )}

      {/* 监控平台 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">监控平台</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex flex-wrap gap-2">
            {brand.platforms.map((platform) => (
              <Badge key={platform} variant="outline" className="px-3 py-1">
                {PLATFORM_MAP[platform] || platform}
              </Badge>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* 竞品列表 */}
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle className="text-base flex items-center gap-2">
            <Users className="h-5 w-5" />
            竞品列表
            <span className="text-sm font-normal text-muted-foreground">
              ({brand.competitors?.length || 0}/5)
            </span>
          </CardTitle>
          <div className="flex items-center gap-2">
            <Button
              size="sm"
              variant="outline"
              onClick={handleLoadRecommendations}
              disabled={(brand.competitors?.length || 0) >= 5}
            >
              <Sparkles className="mr-1 h-4 w-4" />
              推荐竞品
            </Button>
            <Button
              size="sm"
              onClick={() => setShowAddCompetitor(true)}
              disabled={(brand.competitors?.length || 0) >= 5}
            >
              <Plus className="mr-1 h-4 w-4" />
              手动添加
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {/* 推荐竞品区域 */}
          {showRecommendations && (
            <div className="mb-4 rounded-lg border border-dashed border-primary/30 bg-primary/5 p-4">
              <div className="flex items-center gap-2 mb-3">
                <Lightbulb className="h-4 w-4 text-amber-500" />
                <span className="text-sm font-medium">系统推荐竞品</span>
                {brand.industry && (
                  <span className="text-xs text-muted-foreground">
                    (基于{getIndustryLabel(brand.industry)}行业分析)
                  </span>
                )}
              </div>
              {loadingRecommendations ? (
                <div className="flex items-center justify-center py-4">
                  <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
                  <span className="ml-2 text-sm text-muted-foreground">
                    正在分析推荐...
                  </span>
                </div>
              ) : recommendations.length > 0 ? (
                <div className="grid gap-2 sm:grid-cols-2">
                  {recommendations.map((rec) => {
                    const alreadyAdded = brand.competitors?.some(
                      (c) => c.name === rec.name,
                    );
                    return (
                      <div
                        key={rec.name}
                        className="flex items-center justify-between rounded-md border bg-card p-2.5"
                      >
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium truncate">
                            {rec.name}
                          </p>
                          <p className="text-xs text-muted-foreground truncate">
                            {rec.reason}
                          </p>
                        </div>
                        <Button
                          size="sm"
                          variant={alreadyAdded ? "ghost" : "outline"}
                          className="ml-2 shrink-0"
                          disabled={
                            alreadyAdded ||
                            (brand.competitors?.length || 0) >= 5
                          }
                          onClick={() =>
                            handleAddRecommendedCompetitor(rec.name)
                          }
                        >
                          {alreadyAdded ? (
                            <Check className="h-3 w-3 text-muted-foreground" />
                          ) : (
                            <Plus className="h-3 w-3" />
                          )}
                        </Button>
                      </div>
                    );
                  })}
                </div>
              ) : (
                <p className="text-sm text-muted-foreground py-2">
                  暂无推荐竞品，请手动添加
                </p>
              )}
            </div>
          )}

          {!brand.competitors || brand.competitors.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
              <Users className="mb-2 h-10 w-10 opacity-50" />
              <p>暂无竞品</p>
              <p className="text-sm">添加竞品进行对比分析</p>
            </div>
          ) : (
            <div className="space-y-3">
              {brand.competitors.map((competitor) => (
                <div
                  key={competitor.id}
                  className="flex items-center justify-between rounded-lg border p-3"
                >
                  <div>
                    <p className="font-semibold">{competitor.name}</p>
                    {competitor.aliases && competitor.aliases.length > 0 && (
                      <div className="flex gap-1 mt-1">
                        {competitor.aliases.map((alias, index) => (
                          <Badge
                            key={index}
                            variant="secondary"
                            className="text-xs"
                          >
                            {alias}
                          </Badge>
                        ))}
                      </div>
                    )}
                    <p className="text-xs text-muted-foreground mt-1">
                      上次查询: {formatDate(competitor.last_queried_at)}
                    </p>
                  </div>
                  <div className="flex items-center gap-3">
                    <div className="text-right">
                      <p className="text-sm text-muted-foreground">评分</p>
                      <p className="text-xl font-bold">
                        {competitor.score ?? "-"}
                      </p>
                    </div>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="text-destructive hover:text-destructive"
                      onClick={() => setDeleteCompetitor(competitor)}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* 添加竞品对话框 */}
      <Dialog open={showAddCompetitor} onOpenChange={setShowAddCompetitor}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>添加竞品</DialogTitle>
            <DialogDescription>添加一个竞品品牌进行对比分析</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="competitor-name">
                竞品名称 <span className="text-destructive">*</span>
              </Label>
              <Input
                id="competitor-name"
                value={competitorName}
                onChange={(e) => setCompetitorName(e.target.value)}
                placeholder="请输入竞品名称"
                maxLength={50}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="competitor-aliases">竞品别名</Label>
              <Input
                id="competitor-aliases"
                value={competitorAliases}
                onChange={(e) => setCompetitorAliases(e.target.value)}
                placeholder="多个别名用逗号分隔"
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowAddCompetitor(false)}
              disabled={addingCompetitor}
            >
              取消
            </Button>
            <Button
              onClick={handleAddCompetitor}
              disabled={addingCompetitor || !competitorName.trim()}
            >
              {addingCompetitor && (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              )}
              添加
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除竞品确认对话框 */}
      <Dialog
        open={!!deleteCompetitor}
        onOpenChange={() => setDeleteCompetitor(null)}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
            <DialogDescription>
              确定要删除竞品 &ldquo;{deleteCompetitor?.name}&rdquo; 吗？
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setDeleteCompetitor(null)}
              disabled={deletingCompetitor}
            >
              取消
            </Button>
            <Button
              variant="destructive"
              onClick={handleDeleteCompetitor}
              disabled={deletingCompetitor}
            >
              {deletingCompetitor ? "删除中..." : "确认删除"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 下一步行动建议 */}
      <NextActionCard
        context={
          {
            hasData: !!brand,
            hasBrands: !!brand,
            brandCount: 1,
            overallScore: brand?.score?.overall ?? 0,
            scoreChange: 0,
            competitorCount: brand?.competitors?.length ?? 0,
            hasQueryHistory: !!brand?.last_queried_at,
            currentPage: "brand",
            brandId: brandId,
          } as ActionContext
        }
      />
    </div>
  );
}
