"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Sparkles, ChevronDown, ChevronUp, Trash2, Eye, EyeOff,
  Zap, Clock, BarChart3, CheckCircle, AlertCircle, Loader2,
} from "lucide-react";

interface Task {
  id: string;
  title: string;
  taskType: string;
  difficulty: number;
  xpReward: number;
  isActive: boolean;
  totalAttempts: number;
  avgScore: number;
}

interface Track {
  id: string;
  slug: string;
  name: string;
  icon: string;
  color: string;
  difficulty: number;
  _count: { tasks: number };
  tasks: Task[];
}

const DIFF_LABELS: Record<number, string> = { 1: "Easy", 2: "Medium", 3: "Hard" };
const DIFF_COLORS: Record<number, string> = {
  1: "text-emerald-400 bg-emerald-500/10 border-emerald-500/30",
  2: "text-yellow-400 bg-yellow-500/10 border-yellow-500/30",
  3: "text-red-400 bg-red-500/10 border-red-500/30",
};

export function AdminPracticeContent({ tracks: initialTracks }: { tracks: Track[] }) {
  const [tracks, setTracks] = useState<Track[]>(initialTracks);
  const [expandedTrack, setExpandedTrack] = useState<string | null>(null);
  const [generating, setGenerating] = useState<string | null>(null);
  const [generateCount, setGenerateCount] = useState<Record<string, number>>({});

  const totalTasks = tracks.reduce((s, t) => s + t._count.tasks, 0);
  const tracksWithTasks = tracks.filter(t => t._count.tasks > 0).length;

  async function handleGenerate(track: Track) {
    const count = generateCount[track.slug] ?? 5;
    setGenerating(track.slug);
    try {
      const res = await fetch("/api/admin/practice/generate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ trackSlug: track.slug, count }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error ?? "Generation failed");

      toast.success(`Generated ${data.created} tasks for ${track.name}`);

      setTracks(prev => prev.map(t => {
        if (t.slug !== track.slug) return t;
        const newTasks = (data.tasks ?? []).map((task: any) => ({
          id: task.id,
          title: task.title,
          taskType: task.taskType,
          difficulty: task.difficulty,
          xpReward: task.xpReward,
          isActive: task.isActive,
          totalAttempts: 0,
          avgScore: 0,
        }));
        return {
          ...t,
          tasks: [...t.tasks, ...newTasks],
          _count: { tasks: t._count.tasks + newTasks.length },
        };
      }));
      setExpandedTrack(track.slug);
    } catch (err: any) {
      toast.error(err.message ?? "Failed to generate tasks");
    } finally {
      setGenerating(null);
    }
  }

  async function handleToggle(trackSlug: string, taskId: string, isActive: boolean) {
    try {
      const res = await fetch("/api/admin/practice/tasks", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ taskId, isActive }),
      });
      if (!res.ok) throw new Error("Update failed");
      setTracks(prev => prev.map(t => {
        if (t.slug !== trackSlug) return t;
        return { ...t, tasks: t.tasks.map(task => task.id === taskId ? { ...task, isActive } : task) };
      }));
    } catch {
      toast.error("Failed to update task");
    }
  }

  async function handleDelete(trackSlug: string, taskId: string) {
    if (!confirm("Delete this task? This cannot be undone.")) return;
    try {
      const res = await fetch(`/api/admin/practice/tasks?taskId=${taskId}`, { method: "DELETE" });
      if (!res.ok) throw new Error("Delete failed");
      toast.success("Task deleted");
      setTracks(prev => prev.map(t => {
        if (t.slug !== trackSlug) return t;
        return {
          ...t,
          tasks: t.tasks.filter(task => task.id !== taskId),
          _count: { tasks: t._count.tasks - 1 },
        };
      }));
    } catch {
      toast.error("Failed to delete task");
    }
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Practice Task Manager</h1>
          <p className="text-muted-foreground text-sm mt-1">
            {totalTasks} tasks across {tracksWithTasks}/{tracks.length} tracks
          </p>
        </div>
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <Sparkles className="h-4 w-4 text-violet-400" />
          AI-powered task generation
        </div>
      </div>

      {/* Stats row */}
      <div className="grid grid-cols-3 gap-4">
        {[
          { label: "Total Tasks", value: totalTasks, icon: <CheckCircle className="h-4 w-4 text-emerald-400" /> },
          { label: "Tracks Covered", value: `${tracksWithTasks}/${tracks.length}`, icon: <BarChart3 className="h-4 w-4 text-violet-400" /> },
          { label: "Missing Coverage", value: tracks.length - tracksWithTasks, icon: <AlertCircle className="h-4 w-4 text-amber-400" /> },
        ].map(s => (
          <div key={s.label} className="bg-card border border-border/50 rounded-xl p-4 flex items-center gap-3">
            {s.icon}
            <div>
              <p className="text-xl font-bold">{s.value}</p>
              <p className="text-xs text-muted-foreground">{s.label}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Track list */}
      <div className="space-y-3">
        {tracks.map(track => {
          const isExpanded = expandedTrack === track.slug;
          const isGenerating = generating === track.slug;
          const count = generateCount[track.slug] ?? 5;
          const hasTasks = track._count.tasks > 0;

          return (
            <div
              key={track.slug}
              className={cn(
                "bg-card border rounded-xl overflow-hidden transition-all",
                hasTasks ? "border-border/50" : "border-amber-500/30",
              )}
            >
              {/* Track header */}
              <div className="flex items-center gap-4 p-4">
                <span className="text-2xl">{track.icon}</span>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <p className="font-semibold truncate">{track.name}</p>
                    {!hasTasks && (
                      <Badge className="text-xs bg-amber-500/10 text-amber-400 border-amber-500/30">
                        No tasks
                      </Badge>
                    )}
                  </div>
                  <p className="text-xs text-muted-foreground">{track._count.tasks} tasks</p>
                </div>

                {/* Generate controls */}
                <div className="flex items-center gap-2">
                  <select
                    value={count}
                    onChange={e => setGenerateCount(prev => ({ ...prev, [track.slug]: Number(e.target.value) }))}
                    className="text-xs bg-background border border-border rounded px-2 py-1 text-foreground"
                    disabled={isGenerating}
                  >
                    {[3, 5, 7, 10].map(n => <option key={n} value={n}>{n} tasks</option>)}
                  </select>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleGenerate(track)}
                    disabled={isGenerating || generating !== null}
                    className="gap-1.5 text-xs"
                  >
                    {isGenerating ? (
                      <><Loader2 className="h-3 w-3 animate-spin" /> Generating...</>
                    ) : (
                      <><Sparkles className="h-3 w-3 text-violet-400" /> Generate</>
                    )}
                  </Button>
                  {hasTasks && (
                    <button
                      type="button"
                      onClick={() => setExpandedTrack(isExpanded ? null : track.slug)}
                      className="text-muted-foreground hover:text-foreground transition-colors p-1"
                    >
                      {isExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
                    </button>
                  )}
                </div>
              </div>

              {/* Task list */}
              <AnimatePresence>
                {isExpanded && hasTasks && (
                  <motion.div
                    initial={{ height: 0 }}
                    animate={{ height: "auto" }}
                    exit={{ height: 0 }}
                    className="overflow-hidden border-t border-border/50"
                  >
                    <div className="divide-y divide-border/30">
                      {track.tasks.map(task => (
                        <div key={task.id} className={cn("flex items-center gap-3 px-4 py-3", !task.isActive && "opacity-50")}>
                          <div className="flex-1 min-w-0">
                            <p className="text-sm font-medium truncate">{task.title}</p>
                            <div className="flex items-center gap-2 mt-1">
                              <span className={cn("text-xs px-1.5 py-0.5 rounded border", DIFF_COLORS[task.difficulty])}>
                                {DIFF_LABELS[task.difficulty]}
                              </span>
                              <span className="text-xs text-muted-foreground">{task.taskType.replace(/_/g, " ")}</span>
                            </div>
                          </div>
                          <div className="flex items-center gap-3 text-xs text-muted-foreground shrink-0">
                            <span className="flex items-center gap-1"><Zap className="h-3 w-3" />{task.xpReward} XP</span>
                            <span className="flex items-center gap-1"><BarChart3 className="h-3 w-3" />{task.totalAttempts}</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <button
                              type="button"
                              title={task.isActive ? "Disable task" : "Enable task"}
                              onClick={() => handleToggle(track.slug, task.id, !task.isActive)}
                              className="p-1.5 rounded hover:bg-muted transition-colors text-muted-foreground hover:text-foreground"
                            >
                              {task.isActive ? <Eye className="h-3.5 w-3.5" /> : <EyeOff className="h-3.5 w-3.5" />}
                            </button>
                            <button
                              type="button"
                              title="Delete task"
                              onClick={() => handleDelete(track.slug, task.id)}
                              className="p-1.5 rounded hover:bg-red-500/10 transition-colors text-muted-foreground hover:text-red-400"
                            >
                              <Trash2 className="h-3.5 w-3.5" />
                            </button>
                          </div>
                        </div>
                      ))}
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          );
        })}
      </div>
    </div>
  );
}
