import { useAuth } from "@/_core/hooks/useAuth";
import { trpc } from "@/lib/trpc";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Progress } from "@/components/ui/progress";
import { ScrollArea } from "@/components/ui/scroll-area";
import { toast } from "sonner";
import { useState, useMemo } from "react";
import {
  BookOpen, Play, CheckCircle2, Star, Target,
  ChevronRight, Filter, AlertTriangle, Lightbulb,
  ArrowUpDown, Clock, Dumbbell
} from "lucide-react";

const CATEGORY_LABELS: Record<string, { label: string; icon: React.ReactNode; color: string }> = {
  forehand: { label: "正手", icon: <Target className="w-4 h-4" />, color: "bg-green-100 text-green-700" },
  backhand: { label: "反手", icon: <ArrowUpDown className="w-4 h-4" />, color: "bg-blue-100 text-blue-700" },
  serve: { label: "发球", icon: <Dumbbell className="w-4 h-4" />, color: "bg-purple-100 text-purple-700" },
  volley: { label: "截击", icon: <Target className="w-4 h-4" />, color: "bg-orange-100 text-orange-700" },
  footwork: { label: "脚步", icon: <Dumbbell className="w-4 h-4" />, color: "bg-yellow-100 text-yellow-700" },
  shadow: { label: "影子挥拍", icon: <Play className="w-4 h-4" />, color: "bg-indigo-100 text-indigo-700" },
  wall: { label: "墙壁练习", icon: <Target className="w-4 h-4" />, color: "bg-pink-100 text-pink-700" },
  fitness: { label: "体能", icon: <Dumbbell className="w-4 h-4" />, color: "bg-red-100 text-red-700" },
  strategy: { label: "战术", icon: <Lightbulb className="w-4 h-4" />, color: "bg-teal-100 text-teal-700" },
};

const SKILL_LABELS: Record<string, { label: string; color: string }> = {
  beginner: { label: "初级", color: "bg-emerald-100 text-emerald-700" },
  intermediate: { label: "中级", color: "bg-amber-100 text-amber-700" },
  advanced: { label: "高级", color: "bg-rose-100 text-rose-700" },
};

export default function Tutorials() {
  const { user } = useAuth();
  const [selectedCategory, setSelectedCategory] = useState<string>("all");
  const [selectedSkill, setSelectedSkill] = useState<string>("all");
  const [selectedTutorial, setSelectedTutorial] = useState<number | null>(null);
  const [notes, setNotes] = useState("");

  const { data: tutorials, isLoading } = trpc.tutorial.list.useQuery({
    category: selectedCategory === "all" ? undefined : selectedCategory,
    skillLevel: selectedSkill === "all" ? undefined : selectedSkill,
  });

  const { data: progressData } = trpc.tutorial.progress.useQuery(undefined, { enabled: !!user });

  const updateProgress = trpc.tutorial.updateProgress.useMutation({
    onSuccess: () => toast.success("进度已更新"),
  });

  const progressMap = useMemo(() => {
    const map: Record<number, any> = {};
    progressData?.forEach((p: any) => { map[p.tutorialId] = p; });
    return map;
  }, [progressData]);

  const totalTutorials = tutorials?.length || 0;
  const watchedCount = tutorials?.filter((t: any) => progressMap[t.id]?.watched).length || 0;
  const progressPercent = totalTutorials > 0 ? Math.round((watchedCount / totalTutorials) * 100) : 0;

  const categories = useMemo(() => {
    const cats = new Set<string>();
    tutorials?.forEach((t: any) => cats.add(t.category));
    return Array.from(cats);
  }, [tutorials]);

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

  const handleSaveNotes = (tutorialId: number) => {
    updateProgress.mutate({ tutorialId, notes });
    setNotes("");
    toast.success("笔记已保存");
  };

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

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

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold flex items-center gap-2">
          <BookOpen className="w-6 h-6 text-primary" />
          教程库
        </h1>
        <p className="text-muted-foreground mt-1">查看动作分解、要点说明和常见错误</p>
      </div>

      {/* Progress Overview */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium">学习进度</span>
            <span className="text-sm text-muted-foreground">{watchedCount}/{totalTutorials} 已学习</span>
          </div>
          <Progress value={progressPercent} className="h-2" />
          <p className="text-xs text-muted-foreground mt-1">{progressPercent}% 完成</p>
        </CardContent>
      </Card>

      {/* Filters */}
      <div className="flex flex-wrap gap-3">
        <div className="flex items-center gap-2">
          <Filter className="w-4 h-4 text-muted-foreground" />
          <span className="text-sm font-medium">分类:</span>
        </div>
        <div className="flex flex-wrap gap-1.5">
          <Button
            variant={selectedCategory === "all" ? "default" : "outline"}
            size="sm"
            onClick={() => setSelectedCategory("all")}
          >
            全部
          </Button>
          {Object.entries(CATEGORY_LABELS).map(([key, { label, icon }]) => (
            <Button
              key={key}
              variant={selectedCategory === key ? "default" : "outline"}
              size="sm"
              onClick={() => setSelectedCategory(key)}
              className="gap-1"
            >
              {icon} {label}
            </Button>
          ))}
        </div>
      </div>

      <div className="flex flex-wrap gap-3">
        <div className="flex items-center gap-2">
          <Star className="w-4 h-4 text-muted-foreground" />
          <span className="text-sm font-medium">级别:</span>
        </div>
        <div className="flex gap-1.5">
          <Button
            variant={selectedSkill === "all" ? "default" : "outline"}
            size="sm"
            onClick={() => setSelectedSkill("all")}
          >
            全部
          </Button>
          {Object.entries(SKILL_LABELS).map(([key, { label }]) => (
            <Button
              key={key}
              variant={selectedSkill === key ? "default" : "outline"}
              size="sm"
              onClick={() => setSelectedSkill(key)}
            >
              {label}
            </Button>
          ))}
        </div>
      </div>

      {/* Tutorial Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {tutorials?.map((tutorial: any) => {
          const cat = CATEGORY_LABELS[tutorial.category] || { label: tutorial.category, color: "bg-gray-100 text-gray-700" };
          const skill = SKILL_LABELS[tutorial.skillLevel] || { label: tutorial.skillLevel, color: "bg-gray-100 text-gray-700" };
          const progress = progressMap[tutorial.id];
          const isWatched = progress?.watched === 1;
          const keyPoints = typeof tutorial.keyPoints === "string" ? JSON.parse(tutorial.keyPoints) : tutorial.keyPoints || [];
          const mistakes = typeof tutorial.commonMistakes === "string" ? JSON.parse(tutorial.commonMistakes) : tutorial.commonMistakes || [];

          return (
            <Dialog key={tutorial.id}>
              <DialogTrigger asChild>
                <Card className={`cursor-pointer hover:shadow-md transition-all ${isWatched ? "border-green-300 bg-green-50/30" : ""}`}>
                  <CardHeader className="pb-3">
                    <div className="flex items-start justify-between">
                      <div className="flex gap-2 flex-wrap">
                        <Badge variant="secondary" className={cat.color}>{cat.label}</Badge>
                        <Badge variant="secondary" className={skill.color}>{skill.label}</Badge>
                      </div>
                      {isWatched && <CheckCircle2 className="w-5 h-5 text-green-600 shrink-0" />}
                    </div>
                    <CardTitle className="text-base mt-2">{tutorial.title}</CardTitle>
                    <CardDescription className="line-clamp-2">{tutorial.description}</CardDescription>
                  </CardHeader>
                  <CardContent className="pt-0">
                    <div className="flex items-center justify-between text-xs text-muted-foreground">
                      <span className="flex items-center gap-1">
                        <Clock className="w-3 h-3" />
                        {Math.round((tutorial.duration || 0) / 60)}分钟
                      </span>
                      <span className="flex items-center gap-1">
                        {keyPoints.length}个要点
                        <ChevronRight className="w-3 h-3" />
                      </span>
                    </div>
                    {progress?.selfScore && (
                      <div className="flex items-center gap-1 mt-2">
                        {[1, 2, 3, 4, 5].map(s => (
                          <Star key={s} className={`w-3 h-3 ${s <= progress.selfScore ? "fill-yellow-400 text-yellow-400" : "text-gray-300"}`} />
                        ))}
                        <span className="text-xs text-muted-foreground ml-1">自评</span>
                      </div>
                    )}
                  </CardContent>
                </Card>
              </DialogTrigger>

              <DialogContent className="max-w-2xl max-h-[85vh] overflow-hidden flex flex-col">
                <DialogHeader>
                  <div className="flex gap-2 mb-2">
                    <Badge variant="secondary" className={cat.color}>{cat.label}</Badge>
                    <Badge variant="secondary" className={skill.color}>{skill.label}</Badge>
                    <Badge variant="outline" className="gap-1">
                      <Clock className="w-3 h-3" />
                      {Math.round((tutorial.duration || 0) / 60)}分钟
                    </Badge>
                  </div>
                  <DialogTitle className="text-xl">{tutorial.title}</DialogTitle>
                </DialogHeader>

                <ScrollArea className="flex-1 pr-4">
                  <div className="space-y-5">
                    <p className="text-muted-foreground">{tutorial.description}</p>

                    {/* Key Points */}
                    <div>
                      <h3 className="font-semibold flex items-center gap-2 mb-3">
                        <Lightbulb className="w-4 h-4 text-yellow-500" />
                        技术要点
                      </h3>
                      <div className="space-y-2">
                        {keyPoints.map((point: string, i: number) => (
                          <div key={i} className="flex items-start gap-2 p-2 rounded-lg bg-green-50 border border-green-100">
                            <CheckCircle2 className="w-4 h-4 text-green-600 mt-0.5 shrink-0" />
                            <span className="text-sm">{point}</span>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* Common Mistakes */}
                    <div>
                      <h3 className="font-semibold flex items-center gap-2 mb-3">
                        <AlertTriangle className="w-4 h-4 text-orange-500" />
                        常见错误
                      </h3>
                      <div className="space-y-2">
                        {mistakes.map((mistake: string, i: number) => (
                          <div key={i} className="flex items-start gap-2 p-2 rounded-lg bg-orange-50 border border-orange-100">
                            <AlertTriangle className="w-4 h-4 text-orange-500 mt-0.5 shrink-0" />
                            <span className="text-sm">{mistake}</span>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* Self Assessment */}
                    {user && (
                      <div>
                        <h3 className="font-semibold mb-3">自我评估</h3>
                        <div className="flex items-center gap-2 mb-3">
                          <span className="text-sm text-muted-foreground">掌握程度:</span>
                          {[1, 2, 3, 4, 5].map(s => (
                            <button
                              key={s}
                              onClick={() => handleSelfScore(tutorial.id, s)}
                              className="hover:scale-110 transition-transform"
                            >
                              <Star className={`w-6 h-6 ${s <= (progress?.selfScore || 0) ? "fill-yellow-400 text-yellow-400" : "text-gray-300 hover:text-yellow-300"}`} />
                            </button>
                          ))}
                        </div>

                        <Textarea
                          placeholder="记录学习笔记和心得..."
                          value={notes || progress?.notes || ""}
                          onChange={e => setNotes(e.target.value)}
                          className="mb-2"
                          rows={3}
                        />
                        <div className="flex gap-2">
                          <Button size="sm" onClick={() => handleSaveNotes(tutorial.id)}>
                            保存笔记
                          </Button>
                          {!isWatched && (
                            <Button size="sm" variant="outline" onClick={() => handleMarkWatched(tutorial.id)} className="gap-1">
                              <CheckCircle2 className="w-4 h-4" />
                              标记已学习
                            </Button>
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                </ScrollArea>
              </DialogContent>
            </Dialog>
          );
        })}
      </div>

      {tutorials?.length === 0 && (
        <div className="text-center py-12 text-muted-foreground">
          <BookOpen className="w-12 h-12 mx-auto mb-3 opacity-50" />
          <p>暂无匹配的教程</p>
        </div>
      )}
    </div>
  );
}
