import { useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { Card, CardContent } 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 { Checkbox } from "@/components/ui/checkbox";
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, Target } from "lucide-react";
import { useChapters, useCreateChapter, useDeleteChapter, useUnlockChapter, useLockChapter, useCourse } from "@/hooks/queries";
import { useQuery } from "@tanstack/react-query";
import { taxonomyService, lmsService } from "@/services";
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 navigate = useNavigate();
  const { toast } = useToast();
  const { data: chapters = [], isLoading } = useChapters(cid);
  const { data: course } = useCourse(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 [topicId, setTopicId] = useState<number | null>(null);
  const [selectedObjectiveIds, setSelectedObjectiveIds] = useState<number[]>([]);

  const subjectId = course?.encoach_subject_id;

  const { data: topics = [] } = useQuery({
    queryKey: ["taxonomy", "topics", subjectId],
    queryFn: () => subjectId ? taxonomyService.listTopics({ subject_id: subjectId }) : Promise.resolve([]),
    enabled: !!subjectId,
  });

  const { data: objectivesData } = useQuery({
    queryKey: ["lms", "objectives", topicId],
    queryFn: () => topicId ? lmsService.listLearningObjectives({ topic_id: topicId }) : Promise.resolve({ items: [], total: 0 }),
    enabled: !!topicId,
  });
  const objectives = objectivesData?.items ?? [];

  const selectedTopic = topics.find((t) => t.id === topicId);

  const resetForm = () => {
    setName(""); setDescription(""); setStartDate(""); setUnlockMode("manual");
    setTopicId(null); setSelectedObjectiveIds([]);
  };

  const handleCreate = () => {
    createChapter.mutate(
      {
        courseId: cid,
        data: {
          name,
          course_id: cid,
          description,
          start_date: startDate || undefined,
          unlock_mode: unlockMode,
          topic_id: topicId ?? undefined,
          learning_objective_ids: selectedObjectiveIds.length > 0 ? selectedObjectiveIds : undefined,
        },
      },
      {
        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 className="sm:max-w-[520px] max-h-[85vh] overflow-y-auto">
            <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="grid grid-cols-2 gap-4">
                <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>
              </div>

              {topics.length > 0 && (
                <div className="space-y-2">
                  <Label>Topic</Label>
                  <Select
                    value={topicId ? String(topicId) : "none"}
                    onValueChange={(v) => {
                      setTopicId(v === "none" ? null : Number(v));
                      setSelectedObjectiveIds([]);
                    }}
                  >
                    <SelectTrigger><SelectValue placeholder="Select topic..." /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="none">None</SelectItem>
                      {topics.map((t) => (
                        <SelectItem key={t.id} value={String(t.id)}>{t.name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  {selectedTopic && (
                    <p className="text-xs text-muted-foreground">
                      Domain: <strong>{selectedTopic.domain_name}</strong>
                    </p>
                  )}
                </div>
              )}

              {topicId && objectives.length > 0 && (
                <div className="space-y-2">
                  <Label>
                    <Target className="inline h-3.5 w-3.5 mr-1" />
                    Learning Objectives ({selectedObjectiveIds.length} selected)
                  </Label>
                  <div className="border rounded-md p-3 max-h-[140px] overflow-y-auto space-y-1">
                    {objectives.map((o) => (
                      <label key={o.id} className="flex items-center gap-2 text-sm cursor-pointer hover:bg-muted/50 p-1 rounded">
                        <Checkbox
                          checked={selectedObjectiveIds.includes(o.id)}
                          onCheckedChange={() =>
                            setSelectedObjectiveIds((prev) =>
                              prev.includes(o.id)
                                ? prev.filter((x) => x !== o.id)
                                : [...prev, o.id]
                            )
                          }
                        />
                        <span className="flex-1">{o.name}</span>
                        {o.bloom_level && (
                          <Badge variant="outline" className="text-[10px] capitalize">
                            {o.bloom_level}
                          </Badge>
                        )}
                      </label>
                    ))}
                  </div>
                </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 cursor-pointer" onClick={() => navigate(`/teacher/courses/${cid}/chapters/${ch.id}`)}>
              <CardContent className="flex items-center gap-4 py-4">
                <GripVertical className="h-5 w-5 text-muted-foreground shrink-0 cursor-grab" onClick={e => e.stopPropagation()} />
                <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>
                    {ch.topic_name && (
                      <Badge variant="outline" className="text-[10px] shrink-0">{ch.topic_name}</Badge>
                    )}
                    {ch.domain_name && (
                      <span className="text-[10px] text-muted-foreground shrink-0">({ch.domain_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>
                    {(ch.learning_objective_ids?.length ?? 0) > 0 && (
                      <span className="flex items-center gap-0.5">
                        <Target className="h-3 w-3" />
                        {ch.learning_objective_ids?.length} objective{(ch.learning_objective_ids?.length ?? 0) !== 1 ? "s" : ""}
                      </span>
                    )}
                  </div>
                </div>
                <Badge variant={ch.is_unlocked ? "default" : "secondary"}>
                  {ch.is_unlocked ? "Unlocked" : "Locked"}
                </Badge>
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={(e) => { e.stopPropagation(); 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={(e) => { e.stopPropagation(); 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>
  );
}
