import { useState } from "react";
import { useParams } from "react-router-dom";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Plus, GripVertical, Lock, Unlock, Trash2, Loader2, BookOpen } from "lucide-react";
import { useChapters, useCreateChapter, useDeleteChapter, useUnlockChapter, useLockChapter } from "@/hooks/queries";
import { useToast } from "@/hooks/use-toast";
import type { ChapterUnlockMode } from "@/types/courseware";

export default function CourseChapters() {
  const { courseId } = useParams<{ courseId: string }>();
  const cid = Number(courseId);
  const { toast } = useToast();
  const { data: chapters = [], isLoading } = useChapters(cid);
  const createChapter = useCreateChapter();
  const deleteChapter = useDeleteChapter();
  const unlockChapter = useUnlockChapter();
  const lockChapter = useLockChapter();

  const [showAdd, setShowAdd] = useState(false);
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [startDate, setStartDate] = useState("");
  const [unlockMode, setUnlockMode] = useState<ChapterUnlockMode>("manual");

  const resetForm = () => { setName(""); setDescription(""); setStartDate(""); setUnlockMode("manual"); };

  const handleCreate = () => {
    createChapter.mutate(
      { courseId: cid, data: { name, course_id: cid, description, start_date: startDate || undefined, unlock_mode: unlockMode } },
      {
        onSuccess: () => { toast({ title: "Chapter Created" }); setShowAdd(false); resetForm(); },
        onError: () => toast({ title: "Error", description: "Failed to create chapter", variant: "destructive" }),
      },
    );
  };

  const handleDelete = (id: number) => {
    deleteChapter.mutate(
      { id, courseId: cid },
      {
        onSuccess: () => toast({ title: "Chapter Deleted" }),
        onError: () => toast({ title: "Error", description: "Failed to delete chapter", variant: "destructive" }),
      },
    );
  };

  const handleToggleLock = (id: number, isUnlocked: boolean) => {
    const mutation = isUnlocked ? lockChapter : unlockChapter;
    mutation.mutate(
      { id, courseId: cid },
      {
        onSuccess: () => toast({ title: isUnlocked ? "Chapter Locked" : "Chapter Unlocked" }),
        onError: () => toast({ title: "Error", description: "Failed to update lock status", variant: "destructive" }),
      },
    );
  };

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

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Course Chapters</h1>
          <p className="text-muted-foreground">Manage chapters and their sequence for this course.</p>
        </div>
        <Dialog open={showAdd} onOpenChange={setShowAdd}>
          <DialogTrigger asChild>
            <Button><Plus className="mr-2 h-4 w-4" /> Add Chapter</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader><DialogTitle>Add New Chapter</DialogTitle></DialogHeader>
            <div className="space-y-4 pt-4">
              <div className="space-y-2">
                <Label>Name</Label>
                <Input placeholder="Chapter name" value={name} onChange={e => setName(e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>Description</Label>
                <Textarea placeholder="Brief description" value={description} onChange={e => setDescription(e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>Start Date</Label>
                <Input type="date" value={startDate} onChange={e => setStartDate(e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>Unlock Mode</Label>
                <Select value={unlockMode} onValueChange={v => setUnlockMode(v as ChapterUnlockMode)}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="manual">Manual</SelectItem>
                    <SelectItem value="auto_date">Auto (Date)</SelectItem>
                    <SelectItem value="prerequisite">Prerequisite</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <Button className="w-full" onClick={handleCreate} disabled={createChapter.isPending || !name}>
                {createChapter.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Create Chapter
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <div className="space-y-3">
        {chapters
          .sort((a, b) => a.sequence - b.sequence)
          .map(ch => (
            <Card key={ch.id} className="hover:shadow-sm transition-shadow">
              <CardContent className="flex items-center gap-4 py-4">
                <GripVertical className="h-5 w-5 text-muted-foreground shrink-0 cursor-grab" />
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <BookOpen className="h-4 w-4 text-primary shrink-0" />
                    <span className="font-medium truncate">{ch.name}</span>
                  </div>
                  <div className="flex items-center gap-3 mt-1 text-xs text-muted-foreground">
                    {ch.start_date && <span>{new Date(ch.start_date).toLocaleDateString()}</span>}
                    <span>{ch.material_count} material{ch.material_count !== 1 ? "s" : ""}</span>
                  </div>
                </div>
                <Badge variant={ch.is_unlocked ? "default" : "secondary"}>
                  {ch.is_unlocked ? "Unlocked" : "Locked"}
                </Badge>
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => handleToggleLock(ch.id, ch.is_unlocked)}
                  disabled={unlockChapter.isPending || lockChapter.isPending}
                >
                  {ch.is_unlocked ? <Lock className="h-4 w-4" /> : <Unlock className="h-4 w-4" />}
                </Button>
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => handleDelete(ch.id)}
                  disabled={deleteChapter.isPending}
                >
                  <Trash2 className="h-4 w-4 text-destructive" />
                </Button>
              </CardContent>
            </Card>
          ))}
        {chapters.length === 0 && (
          <Card>
            <CardContent className="py-12 text-center text-muted-foreground">
              <BookOpen className="h-12 w-12 mx-auto mb-3 opacity-40" />
              <p>No chapters yet. Add your first chapter to get started.</p>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}
