import { useMemo, useState } from "react";
import { useParams } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import {
  BookOpen,
  CheckCircle2,
  CircleDot,
  Lock,
  Sparkles,
  TrendingUp,
  Clock,
  Percent,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { useAiCourse, useAiCourseTracks, useCreateEnglishCourse } from "@/hooks/queries/useAiCourse";
import { queryKeys } from "@/hooks/queries/keys";
import type { AICourseTrack, AIGenerationStep, AITrackModule } from "@/types";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from "recharts";
import { toast } from "sonner";

const DEFAULT_STEPS: AIGenerationStep[] = [
  { name: "Profile Analysis", status: "complete" },
  { name: "Reading Content", status: "in_progress" },
  { name: "Grammar Exercises", status: "pending" },
  { name: "Speaking Prompts", status: "pending" },
  { name: "Vocabulary Sets", status: "pending" },
];

const COLORS = ["hsl(var(--primary))", "hsl(var(--chart-2))", "hsl(var(--chart-3))"];

export default function AiEnglishCourse() {
  const { courseId: cid } = useParams<{ courseId: string }>();
  const courseId = Number(cid);
  const qc = useQueryClient();
  const { data: course, isLoading } = useAiCourse(Number.isFinite(courseId) ? courseId : undefined);
  const { data: tracksRaw } = useAiCourseTracks(Number.isFinite(courseId) ? courseId : undefined);
  const createEnglish = useCreateEnglishCourse();

  const [target, setTarget] = useState("");
  const [learningStyle, setLearningStyle] = useState("");
  const [levelUpOpen, setLevelUpOpen] = useState(false);

  const steps = course?.generation_steps?.length ? course.generation_steps : DEFAULT_STEPS;
  const stepProgress = useMemo(() => {
    const done = steps.filter((s) => s.status === "complete").length;
    return Math.round((done / Math.max(steps.length, 1)) * 100);
  }, [steps]);

  const tracks: AICourseTrack[] = useMemo(() => {
    if (tracksRaw?.length) return tracksRaw;
    return [
      { name: "Grammar Track", progress_percent: 40, modules: placeholderModules("grammar") },
      { name: "Skills Track", progress_percent: 55, modules: placeholderModules("skills") },
      { name: "Vocabulary Track", progress_percent: 20, modules: placeholderModules("vocab") },
    ];
  }, [tracksRaw]);

  const cefrChart = [
    { label: "Start", value: 3.2 },
    { label: "Now", value: 4.1 },
    { label: "Target", value: 5.0 },
  ];

  const timePerTrack = tracks.map((t) => ({ name: t.name.replace(" Track", ""), hours: t.progress_percent / 10 }));

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[320px] text-muted-foreground">
        Loading course…
      </div>
    );
  }

  const ls = learningStyle || course?.learning_style?.join(", ") || "visual, mixed";
  const tgt = target || course?.target_level || "B2";

  return (
    <div className="space-y-8 p-6 max-w-7xl mx-auto">
      <div className="flex flex-col gap-2 md:flex-row md:items-end md:justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">AI English course</h1>
          <p className="text-muted-foreground text-sm">Personalized pathway to your target level</p>
        </div>
        <Button onClick={() => setLevelUpOpen(true)} variant="secondary" size="sm" className="gap-2">
          <Sparkles className="h-4 w-4" />
          Preview celebration
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Profile confirmation</CardTitle>
          <CardDescription>Adjust targets before continuing.</CardDescription>
        </CardHeader>
        <CardContent className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          <div>
            <Label className="text-muted-foreground">Current CEFR</Label>
            <p className="text-lg font-semibold mt-1">{course?.current_level ?? "B1"}</p>
          </div>
          <div className="space-y-2">
            <Label htmlFor="target">Target CEFR</Label>
            <Input id="target" value={tgt} onChange={(e) => setTarget(e.target.value)} />
          </div>
          <div className="space-y-2">
            <Label htmlFor="style">Learning style</Label>
            <Input id="style" value={ls} onChange={(e) => setLearningStyle(e.target.value)} />
          </div>
          <div>
            <Label className="text-muted-foreground">Duration (weeks)</Label>
            <p className="text-lg font-semibold mt-1">{course?.estimated_duration_weeks ?? 8}</p>
          </div>
        </CardContent>
        <CardContent className="pt-0">
          <Button
            disabled={createEnglish.isPending}
            onClick={() => {
              if (!course) return;
              const styles =
                ls.split(",")
                  .map((x) => x.trim())
                  .filter(Boolean).length > 0
                  ? ls.split(",")
                      .map((x) => x.trim())
                      .filter(Boolean)
                  : course?.learning_style ?? ["visual"];
              createEnglish.mutate(
                { cefr_level: tgt || course?.current_level || "B1" },
                {
                  onSuccess: () => {
                    qc.invalidateQueries({ queryKey: queryKeys.aiCourse.course(courseId) });
                    qc.invalidateQueries({ queryKey: queryKeys.aiCourse.tracks(courseId) });
                    toast.success("AI course started.");
                  },
                  onError: (e) => toast.error(e instanceof Error ? e.message : "Could not start"),
                },
              );
            }}
          >
            Start AI Course
          </Button>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Generation progress</CardTitle>
          <CardDescription>Content pipeline for this course</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex justify-between text-sm">
            <span>Overall</span>
            <span>{stepProgress}%</span>
          </div>
          <Progress value={stepProgress} />
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
            {steps.map((s) => (
              <div key={s.name} className="rounded-lg border p-3 text-sm">
                <div className="font-medium leading-tight">{s.name}</div>
                <div className="text-muted-foreground capitalize mt-1">{s.status.replace("_", " ")}</div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <div>
        <h2 className="text-lg font-semibold mb-4">Learning tracks</h2>
        <div className="grid gap-4 lg:grid-cols-3">
          {tracks.map((track) => (
            <Card key={track.name}>
              <CardHeader className="pb-2">
                <CardTitle className="text-base flex items-center gap-2">
                  <BookOpen className="h-4 w-4" />
                  {track.name}
                </CardTitle>
                <CardDescription>{track.progress_percent}% complete</CardDescription>
              </CardHeader>
              <CardContent className="space-y-2">
                <Progress value={track.progress_percent} />
                <Separator className="my-2" />
                <ul className="space-y-2">
                  {track.modules.map((m) => (
                    <li key={m.id} className="flex items-start gap-2 text-sm">
                      <ModuleIcon status={m.status} />
                      <div>
                        <div className="font-medium">{m.title}</div>
                        <div className="text-xs text-muted-foreground">~{m.estimated_hours}h</div>
                      </div>
                    </li>
                  ))}
                </ul>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Progress report</CardTitle>
          <CardDescription>CEFR trajectory and effort</CardDescription>
        </CardHeader>
        <CardContent className="grid gap-8 lg:grid-cols-2">
          <div className="h-64">
            <div className="flex items-center gap-2 text-sm font-medium mb-2">
              <TrendingUp className="h-4 w-4" />
              CEFR gain
            </div>
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={cefrChart}>
                <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                <XAxis dataKey="label" />
                <YAxis domain={[0, 6]} />
                <Tooltip />
                <Bar dataKey="value" fill="hsl(var(--primary))" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
          <div className="h-64">
            <div className="flex items-center gap-2 text-sm font-medium mb-2">
              <Clock className="h-4 w-4" />
              Time per track (relative)
            </div>
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie data={timePerTrack} dataKey="hours" nameKey="name" cx="50%" cy="50%" outerRadius={80}>
                  {timePerTrack.map((_, i) => (
                    <Cell key={i} fill={COLORS[i % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </div>
          <div className="lg:col-span-2 flex items-center gap-2 text-sm text-muted-foreground">
            <Percent className="h-4 w-4" />
            Completion rates follow each track&apos;s module checklist above.
          </div>
        </CardContent>
      </Card>

      <Dialog open={levelUpOpen} onOpenChange={setLevelUpOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Sparkles className="h-5 w-5 text-amber-500" />
              Level up!
            </DialogTitle>
          </DialogHeader>
          <p className="text-sm text-muted-foreground">
            You reached <strong>{course?.target_level ?? tgt}</strong>. The next modules unlock with richer tasks and feedback.
          </p>
          <DialogFooter>
            <Button onClick={() => setLevelUpOpen(false)}>Continue</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

function ModuleIcon({ status }: { status: AITrackModule["status"] }) {
  if (status === "completed") return <CheckCircle2 className="h-4 w-4 text-green-600 shrink-0 mt-0.5" />;
  if (status === "in_progress") return <CircleDot className="h-4 w-4 text-primary shrink-0 mt-0.5" />;
  return <Lock className="h-4 w-4 text-muted-foreground shrink-0 mt-0.5" />;
}

function placeholderModules(prefix: string): AITrackModule[] {
  return [
    { id: 1, title: `${prefix} — Foundations`, status: "completed", estimated_hours: 2 },
    { id: 2, title: `${prefix} — Practice set`, status: "in_progress", estimated_hours: 3 },
    { id: 3, title: `${prefix} — Mastery`, status: "locked", estimated_hours: 4 },
  ];
}
