import { useMemo, useState } from "react";
import { useAuth } from "@/_core/hooks/useAuth";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Textarea } from "@/components/ui/textarea";
import { trpc } from "@/lib/trpc";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import {
  BookOpen,
  CheckCircle2,
  ChevronRight,
  Clock3,
  ExternalLink,
  Flame,
  Star,
  Target,
  Trophy,
  type LucideIcon,
} from "lucide-react";

type TutorialRecord = Record<string, any>;

const CATEGORY_META: Record<string, { label: string; icon: LucideIcon; tone: string }> = {
  forehand: { label: "正手", icon: Target, tone: "bg-green-500/10 text-green-700" },
  backhand: { label: "反手", icon: Target, tone: "bg-blue-500/10 text-blue-700" },
  serve: { label: "发球", icon: Target, tone: "bg-violet-500/10 text-violet-700" },
  volley: { label: "截击", icon: Target, tone: "bg-orange-500/10 text-orange-700" },
  footwork: { label: "脚步", icon: Flame, tone: "bg-yellow-500/10 text-yellow-700" },
  shadow: { label: "影子挥拍", icon: BookOpen, tone: "bg-indigo-500/10 text-indigo-700" },
  wall: { label: "墙壁练习", icon: Target, tone: "bg-pink-500/10 text-pink-700" },
  fitness: { label: "体能", icon: Flame, tone: "bg-rose-500/10 text-rose-700" },
  strategy: { label: "战术", icon: Trophy, tone: "bg-teal-500/10 text-teal-700" },
};

const SKILL_META: Record<string, { label: string; tone: string }> = {
  beginner: { label: "初级", tone: "bg-emerald-500/10 text-emerald-700" },
  intermediate: { label: "中级", tone: "bg-amber-500/10 text-amber-700" },
  advanced: { label: "高级", tone: "bg-rose-500/10 text-rose-700" },
};

function parseStringArray(value: unknown) {
  if (Array.isArray(value)) {
    return value.filter((item): item is string => typeof item === "string");
  }
  if (typeof value === "string") {
    try {
      const parsed = JSON.parse(value);
      return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === "string") : [];
    } catch {
      return [];
    }
  }
  return [];
}

function isTutorialCompleted(progress: TutorialRecord | undefined) {
  return progress?.completed === 1 || progress?.watched === 1;
}

function formatEffortMinutes(tutorial: TutorialRecord) {
  const effort = tutorial.estimatedEffortMinutes || (tutorial.duration ? Math.round(tutorial.duration / 60) : 0);
  return effort > 0 ? `${effort} 分钟` : "按需学习";
}

export default function Tutorials() {
  const { user } = useAuth();
  const utils = trpc.useUtils();
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [selectedSkill, setSelectedSkill] = useState("all");
  const [draftNotes, setDraftNotes] = useState<Record<number, string>>({});

  const tutorialsQuery = trpc.tutorial.list.useQuery({ topicArea: "tennis_skill" });
  const progressQuery = trpc.tutorial.progress.useQuery(undefined, { enabled: !!user });

  const updateProgress = trpc.tutorial.updateProgress.useMutation({
    onSuccess: async () => {
      await utils.tutorial.progress.invalidate();
      toast.success("教程进度已更新");
    },
  });

  const tutorials = tutorialsQuery.data ?? [];
  const progressMap = useMemo(() => {
    const map: Record<number, TutorialRecord> = {};
    (progressQuery.data ?? []).forEach((item: TutorialRecord) => {
      map[item.tutorialId] = item;
    });
    return map;
  }, [progressQuery.data]);

  const filteredTutorials = useMemo(
    () => tutorials.filter((tutorial) => {
      if (selectedCategory !== "all" && tutorial.category !== selectedCategory) return false;
      if (selectedSkill !== "all" && tutorial.skillLevel !== selectedSkill) return false;
      return true;
    }),
    [selectedCategory, selectedSkill, tutorials],
  );

  const categories = useMemo(
    () => Array.from(new Set(tutorials.map((tutorial) => tutorial.category).filter(Boolean))),
    [tutorials],
  );

  const completedTutorials = useMemo(
    () => tutorials.filter((tutorial) => isTutorialCompleted(progressMap[tutorial.id])),
    [progressMap, tutorials],
  );

  const handleSaveNotes = (tutorialId: number) => {
    const notes = draftNotes[tutorialId] ?? progressMap[tutorialId]?.notes ?? "";
    updateProgress.mutate({ tutorialId, notes });
  };

  const handleComplete = (tutorialId: number) => {
    updateProgress.mutate({ tutorialId, completed: 1, watched: 1 });
  };

  const handleSelfScore = (tutorialId: number, score: number) => {
    updateProgress.mutate({ tutorialId, selfScore: score });
  };

  if (tutorialsQuery.isLoading) {
    return (
      <div className="flex min-h-[60vh] items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full border-b-2 border-primary" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <section className="overflow-hidden rounded-[30px] border border-border/60 bg-[radial-gradient(circle_at_top_left,_rgba(34,197,94,0.18),_transparent_24%),radial-gradient(circle_at_82%_18%,_rgba(59,130,246,0.14),_transparent_24%),linear-gradient(135deg,rgba(255,255,255,0.98),rgba(248,250,252,0.96))] p-5 shadow-sm md:p-7">
        <div className="grid gap-4 xl:grid-cols-[minmax(0,1.2fr)_360px]">
          <div>
            <div className="flex flex-wrap items-center gap-2">
              <Badge className="bg-emerald-500/10 text-emerald-700">
                <BookOpen className="mr-1 h-3 w-3" />
                网球教程库
              </Badge>
              <Badge variant="outline">仅保留网球训练相关内容</Badge>
            </div>
            <h1 className="mt-4 text-3xl font-semibold tracking-tight">专注正手、反手、发球、脚步和比赛能力</h1>
            <p className="mt-3 max-w-3xl text-sm leading-7 text-muted-foreground">
              这里现在只保留和网球训练直接相关的教程。你可以按动作类别和水平筛选，记录自评与训练笔记，把教程真正沉淀到自己的日常练习里。
            </p>
          </div>

          <div className="grid gap-3 sm:grid-cols-3 xl:grid-cols-1">
            <Card className="border-0 bg-background/90 shadow-sm">
              <CardHeader className="pb-2">
                <CardDescription>教程总数</CardDescription>
                <CardTitle className="text-3xl">{tutorials.length}</CardTitle>
              </CardHeader>
            </Card>
            <Card className="border-0 bg-background/90 shadow-sm">
              <CardHeader className="pb-2">
                <CardDescription>已完成</CardDescription>
                <CardTitle className="text-3xl">{completedTutorials.length}</CardTitle>
              </CardHeader>
            </Card>
            <Card className="border-0 bg-background/90 shadow-sm">
              <CardHeader className="pb-2">
                <CardDescription>当前筛选</CardDescription>
                <CardTitle className="text-base">
                  {selectedCategory === "all" ? "全部分类" : (CATEGORY_META[selectedCategory] || { label: selectedCategory }).label}
                  {" · "}
                  {selectedSkill === "all" ? "全部级别" : (SKILL_META[selectedSkill] || { label: selectedSkill }).label}
                </CardTitle>
              </CardHeader>
            </Card>
          </div>
        </div>
      </section>

      <section className="space-y-5">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
          <div>
            <h2 className="text-xl font-semibold tracking-tight">网球基础教程</h2>
            <p className="mt-1 text-sm text-muted-foreground">选择一个动作主题，完成学习、自评和训练复盘。</p>
          </div>
          <div className="rounded-2xl border border-border/60 bg-background/85 px-4 py-3 text-sm text-muted-foreground">
            已完成 {completedTutorials.length}/{tutorials.length}
          </div>
        </div>

        <div className="flex flex-wrap gap-3">
          <div className="flex flex-wrap gap-2">
            <Button
              variant={selectedCategory === "all" ? "default" : "outline"}
              size="sm"
              onClick={() => setSelectedCategory("all")}
            >
              全部分类
            </Button>
            {categories.map((category) => (
              <Button
                key={category}
                variant={selectedCategory === category ? "default" : "outline"}
                size="sm"
                onClick={() => setSelectedCategory(category)}
              >
                {(CATEGORY_META[category] || { label: category }).label}
              </Button>
            ))}
          </div>

          <div className="flex flex-wrap gap-2">
            <Button
              variant={selectedSkill === "all" ? "default" : "outline"}
              size="sm"
              onClick={() => setSelectedSkill("all")}
            >
              全部级别
            </Button>
            {Object.entries(SKILL_META).map(([key, meta]) => (
              <Button
                key={key}
                variant={selectedSkill === key ? "default" : "outline"}
                size="sm"
                onClick={() => setSelectedSkill(key)}
              >
                {meta.label}
              </Button>
            ))}
          </div>
        </div>

        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          {filteredTutorials.map((tutorial) => {
            const progress = progressMap[tutorial.id];
            const completed = isTutorialCompleted(progress);
            const category = CATEGORY_META[tutorial.category || "forehand"] || CATEGORY_META.forehand;
            const skill = SKILL_META[tutorial.skillLevel || "beginner"] || SKILL_META.beginner;
            const keyPoints = parseStringArray(tutorial.keyPoints);
            const commonMistakes = parseStringArray(tutorial.commonMistakes);

            return (
              <Dialog key={tutorial.id}>
                <Card className={cn(
                  "overflow-hidden border-0 shadow-sm transition-shadow hover:shadow-md",
                  completed && "ring-1 ring-emerald-200",
                )}>
                  <div className="relative h-48 overflow-hidden bg-[radial-gradient(circle_at_top_left,_rgba(34,197,94,0.28),_transparent_30%),radial-gradient(circle_at_bottom_right,_rgba(59,130,246,0.18),_transparent_28%),linear-gradient(135deg,rgba(255,255,255,1),rgba(248,250,252,0.92))] px-5 py-4">
                    {tutorial.thumbnailUrl ? (
                      <>
                        <img
                          src={tutorial.thumbnailUrl}
                          alt={`${tutorial.title} 标准配图`}
                          loading="lazy"
                          className="absolute inset-0 h-full w-full object-cover"
                        />
                        <div className="absolute inset-0 bg-[linear-gradient(180deg,rgba(15,23,42,0.18),rgba(15,23,42,0.58))]" />
                      </>
                    ) : null}

                    <div className="relative flex items-start justify-between gap-3">
                      <div className="flex flex-wrap gap-2">
                        <Badge className={category.tone}>{category.label}</Badge>
                        <Badge className={skill.tone}>{skill.label}</Badge>
                      </div>
                      {completed ? <CheckCircle2 className="h-5 w-5 text-emerald-600" /> : null}
                    </div>

                    <div className="relative mt-6">
                      <div className={cn("text-xl font-semibold", tutorial.thumbnailUrl && "text-white drop-shadow-sm")}>{tutorial.title}</div>
                      <div className={cn(
                        "mt-2 line-clamp-2 text-sm leading-6",
                        tutorial.thumbnailUrl ? "text-white/88 drop-shadow-sm" : "text-muted-foreground",
                      )}>
                        {tutorial.description}
                      </div>
                    </div>
                  </div>

                  <CardContent className="p-5">
                    <div className="flex items-center justify-between text-xs text-muted-foreground">
                      <span className="inline-flex items-center gap-1">
                        <Clock3 className="h-3.5 w-3.5" />
                        {formatEffortMinutes(tutorial)}
                      </span>
                      <span>{keyPoints.length} 个要点</span>
                    </div>

                    {progress?.selfScore ? (
                      <div className="mt-3 flex items-center gap-1">
                        {[1, 2, 3, 4, 5].map((score) => (
                          <Star
                            key={score}
                            className={cn(
                              "h-4 w-4",
                              score <= progress.selfScore ? "fill-yellow-400 text-yellow-400" : "text-slate-300",
                            )}
                          />
                        ))}
                      </div>
                    ) : null}

                    <DialogTrigger asChild>
                      <Button variant="outline" className="mt-4 w-full">查看详情</Button>
                    </DialogTrigger>
                  </CardContent>
                </Card>

                <DialogContent className="max-h-[85vh] max-w-2xl overflow-hidden">
                  <DialogHeader>
                    <div className="flex flex-wrap gap-2">
                      <Badge className={category.tone}>{category.label}</Badge>
                      <Badge className={skill.tone}>{skill.label}</Badge>
                    </div>
                    <DialogTitle className="text-xl">{tutorial.title}</DialogTitle>
                  </DialogHeader>

                  <ScrollArea className="max-h-[68vh] pr-4">
                    <div className="space-y-5">
                      {tutorial.thumbnailUrl ? (
                        <div className="overflow-hidden rounded-[24px] border border-border/60 bg-muted/20">
                          <img
                            src={tutorial.thumbnailUrl}
                            alt={`${tutorial.title} 标准配图`}
                            loading="lazy"
                            className="h-64 w-full object-cover sm:h-80"
                          />
                        </div>
                      ) : null}

                      <p className="text-sm leading-7 text-muted-foreground">{tutorial.description}</p>

                      {tutorial.externalUrl ? (
                        <div className="flex flex-wrap items-center gap-2 rounded-2xl border border-border/60 bg-muted/20 px-4 py-3 text-sm text-muted-foreground">
                          <span>标准配图来源</span>
                          <a
                            href={tutorial.externalUrl}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-flex items-center gap-1 font-medium text-primary underline-offset-4 hover:underline"
                          >
                            Wikimedia Commons
                            <ExternalLink className="h-3.5 w-3.5" />
                          </a>
                        </div>
                      ) : null}

                      <div>
                        <h4 className="text-sm font-semibold uppercase tracking-[0.24em] text-muted-foreground">技术要点</h4>
                        <div className="mt-3 space-y-2">
                          {keyPoints.map((item) => (
                            <div key={item} className="rounded-2xl border border-emerald-200 bg-emerald-50/70 px-4 py-3 text-sm">
                              {item}
                            </div>
                          ))}
                        </div>
                      </div>

                      <div>
                        <h4 className="text-sm font-semibold uppercase tracking-[0.24em] text-muted-foreground">常见错误</h4>
                        <div className="mt-3 space-y-2">
                          {commonMistakes.map((item) => (
                            <div key={item} className="rounded-2xl border border-amber-200 bg-amber-50/70 px-4 py-3 text-sm">
                              {item}
                            </div>
                          ))}
                        </div>
                      </div>

                      {user ? (
                        <div className="rounded-[24px] border border-border/60 bg-muted/20 p-5">
                          <div className="flex flex-wrap items-center justify-between gap-3">
                            <div>
                              <div className="text-base font-semibold">自我评估与训练笔记</div>
                              <div className="mt-1 text-sm text-muted-foreground">学完后给自己打分，并记录本次训练最需要修正的点。</div>
                            </div>
                            {!completed ? (
                              <Button size="sm" onClick={() => handleComplete(tutorial.id)}>
                                标记已学习
                                <CheckCircle2 className="h-4 w-4" />
                              </Button>
                            ) : (
                              <Badge className="bg-emerald-500/10 text-emerald-700">
                                <CheckCircle2 className="mr-1 h-3 w-3" />
                                已完成
                              </Badge>
                            )}
                          </div>

                          <div className="mt-5">
                            <div className="mb-2 text-sm font-medium">掌握程度</div>
                            <div className="flex items-center gap-2">
                              {[1, 2, 3, 4, 5].map((score) => (
                                <button
                                  key={score}
                                  onClick={() => handleSelfScore(tutorial.id, score)}
                                  className="transition-transform hover:scale-110"
                                >
                                  <Star className={cn(
                                    "h-6 w-6",
                                    score <= (progress?.selfScore || 0) ? "fill-yellow-400 text-yellow-400" : "text-slate-300",
                                  )} />
                                </button>
                              ))}
                            </div>
                          </div>

                          <div className="mt-5">
                            <div className="mb-2 text-sm font-medium">学习笔记</div>
                            <Textarea
                              rows={4}
                              placeholder="记录今天的挥拍体感、移动节奏、失误原因和下次训练目标。"
                              value={draftNotes[tutorial.id] ?? progress?.notes ?? ""}
                              onChange={(event) => setDraftNotes((current) => ({
                                ...current,
                                [tutorial.id]: event.target.value,
                              }))}
                            />
                            <div className="mt-3 flex gap-2">
                              <Button size="sm" onClick={() => handleSaveNotes(tutorial.id)}>保存笔记</Button>
                            </div>
                          </div>
                        </div>
                      ) : null}

                      {keyPoints.length > 0 ? (
                        <div>
                          <h4 className="text-sm font-semibold uppercase tracking-[0.24em] text-muted-foreground">训练建议</h4>
                          <div className="mt-3 space-y-2">
                            {keyPoints.slice(0, 3).map((item) => (
                              <div key={item} className="flex items-start gap-2 rounded-2xl bg-muted/20 px-4 py-3 text-sm">
                                <ChevronRight className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
                                <span>下次练习时优先检查：{item}</span>
                              </div>
                            ))}
                          </div>
                        </div>
                      ) : null}
                    </div>
                  </ScrollArea>
                </DialogContent>
              </Dialog>
            );
          })}
        </div>

        {filteredTutorials.length === 0 ? (
          <div className="rounded-[26px] border border-dashed border-border/60 px-6 py-14 text-center text-muted-foreground">
            当前筛选下暂无匹配教程。
          </div>
        ) : null}
      </section>
    </div>
  );
}
