import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Plus, ChevronRight, BookOpen, Layers, FileText, Sparkles, Loader2, Trash2, X } from "lucide-react";
import { useSubjects, useTaxonomyTree } from "@/hooks/queries";
import { taxonomyService } from "@/services/taxonomy.service";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useToast } from "@/hooks/use-toast";
import type { Domain, Topic } from "@/types";

export default function TaxonomyManager() {
  const { toast } = useToast();
  const qc = useQueryClient();
  const { data: rawSubjects, isLoading } = useSubjects();
  const subjects = Array.isArray(rawSubjects) ? rawSubjects : [];
  const [selectedSubjectId, setSelectedSubjectId] = useState<number | null>(null);
  const { data: tree, isLoading: loadingTree } = useTaxonomyTree(selectedSubjectId ?? 0);
  const [showAddSubject, setShowAddSubject] = useState(false);
  const [newSubjectName, setNewSubjectName] = useState("");
  const [newSubjectCode, setNewSubjectCode] = useState("");
  const [showAddDomain, setShowAddDomain] = useState(false);
  const [newDomainName, setNewDomainName] = useState("");
  const [showAddTopic, setShowAddTopic] = useState<number | null>(null);
  const [newTopicName, setNewTopicName] = useState("");
  const [newTopicDifficulty, setNewTopicDifficulty] = useState("medium");
  const [newTopicHours, setNewTopicHours] = useState("1");

  const createSubjectMutation = useMutation({
    mutationFn: () => taxonomyService.createSubject({ name: newSubjectName, code: newSubjectCode, is_active: true, mastery_threshold: 80, grading_scale: "percentage", diagnostic_config: { questions_per_domain: 5, total_question_cap: 30, time_limit_minutes: 45, starting_difficulty: "medium", mastery_per_correct: 10, mastery_per_incorrect: -5 } }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["taxonomy", "subjects"] });
      toast({ title: "Subject Created" });
      setShowAddSubject(false);
      setNewSubjectName("");
      setNewSubjectCode("");
    },
    onError: () => toast({ title: "Error", description: "Failed to create subject", variant: "destructive" }),
  });

  const aiSuggestMutation = useMutation({
    mutationFn: (domainId: number) => taxonomyService.aiSuggestTopics(domainId),
    onSuccess: (data) => {
      toast({ title: "AI Suggestions", description: `${data.suggestions.length} topics suggested. Review and add them.` });
    },
    onError: () => toast({ title: "Error", description: "AI suggestion failed", variant: "destructive" }),
  });

  const createDomainMutation = useMutation({
    mutationFn: (data: Partial<Domain>) => taxonomyService.createDomain(data),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["taxonomy"] }); setShowAddDomain(false); setNewDomainName(""); toast({ title: "Domain created" }); },
    onError: () => toast({ title: "Error", description: "Failed to create domain", variant: "destructive" }),
  });

  const deleteDomainMutation = useMutation({
    mutationFn: (id: number) => taxonomyService.deleteDomain(id),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["taxonomy"] }); toast({ title: "Domain deleted" }); },
    onError: () => toast({ title: "Error", description: "Failed to delete domain", variant: "destructive" }),
  });

  const createTopicMutation = useMutation({
    mutationFn: (data: Partial<Topic>) => taxonomyService.createTopic(data),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["taxonomy"] }); setShowAddTopic(null); setNewTopicName(""); toast({ title: "Topic created" }); },
    onError: () => toast({ title: "Error", description: "Failed to create topic", variant: "destructive" }),
  });

  const deleteTopicMutation = useMutation({
    mutationFn: (id: number) => taxonomyService.deleteTopic(id),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["taxonomy"] }); toast({ title: "Topic deleted" }); },
    onError: () => toast({ title: "Error", description: "Failed to delete topic", variant: "destructive" }),
  });

  const deleteSubjectMutation = useMutation({
    mutationFn: (id: number) => taxonomyService.deleteSubject(id),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["taxonomy"] }); if (selectedSubjectId === id) setSelectedSubjectId(null); toast({ title: "Subject deleted" }); },
    onError: () => toast({ title: "Error", description: "Failed to delete subject", 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">Taxonomy Manager</h1>
          <p className="text-muted-foreground">Manage subjects, domains, topics, and learning objectives.</p>
        </div>
        <Dialog open={showAddSubject} onOpenChange={setShowAddSubject}>
          <DialogTrigger asChild>
            <Button><Plus className="mr-2 h-4 w-4" /> Add Subject</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader><DialogTitle>Create New Subject</DialogTitle></DialogHeader>
            <div className="space-y-4 pt-4">
              <div className="space-y-2">
                <Label>Subject Name</Label>
                <Input placeholder="e.g. Mathematics" value={newSubjectName} onChange={e => setNewSubjectName(e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>Code</Label>
                <Input placeholder="e.g. MATH" value={newSubjectCode} onChange={e => setNewSubjectCode(e.target.value)} />
              </div>
              <Button className="w-full" onClick={() => createSubjectMutation.mutate()} disabled={createSubjectMutation.isPending || !newSubjectName}>
                {createSubjectMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Create Subject
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <div className="space-y-2">
          <h3 className="text-sm font-medium text-muted-foreground px-1">Subjects</h3>
          {subjects.map(s => (
            <div key={s.id} className={`w-full text-left p-3 rounded-lg border transition-colors flex items-center gap-2 ${selectedSubjectId === s.id ? "bg-primary/10 border-primary" : "hover:bg-accent"}`}>
              <button onClick={() => setSelectedSubjectId(s.id)} className="flex items-center gap-2 flex-1 min-w-0 text-left">
                <BookOpen className="h-4 w-4 shrink-0" />
                <div className="min-w-0">
                  <p className="text-sm font-medium truncate">{s.name}</p>
                  <p className="text-xs text-muted-foreground">{s.code} · {s.domain_count ?? 0} domains · {s.topic_count ?? 0} topics</p>
                </div>
              </button>
              <Button size="sm" variant="ghost" className="text-destructive shrink-0" onClick={() => { if (!window.confirm(`Delete subject "${s.name}"?`)) return; deleteSubjectMutation.mutate(s.id); }}>
                <Trash2 className="h-3 w-3" />
              </Button>
            </div>
          ))}
          {subjects.length === 0 && <p className="text-sm text-muted-foreground px-1">No subjects yet.</p>}
        </div>

        <div className="md:col-span-3">
          {!selectedSubjectId ? (
            <Card><CardContent className="py-12 text-center text-muted-foreground">Select a subject to view its taxonomy tree.</CardContent></Card>
          ) : loadingTree ? (
            <div className="flex items-center justify-center min-h-[300px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>
          ) : tree ? (
            <div className="space-y-4">
              <div className="flex justify-end">
                <Button size="sm" variant="outline" onClick={() => setShowAddDomain(true)}>
                  <Plus className="h-3 w-3 mr-1" /> Add Domain
                </Button>
              </div>
              {(Array.isArray(tree.domains) ? tree.domains : []).map(domain => (
                <Collapsible key={domain.id} defaultOpen>
                  <Card>
                    <CardHeader className="pb-3">
                      <CollapsibleTrigger className="flex items-center justify-between w-full">
                        <div className="flex items-center gap-2">
                          <ChevronRight className="h-4 w-4 transition-transform group-data-[state=open]:rotate-90" />
                          <Layers className="h-4 w-4 text-primary" />
                          <CardTitle className="text-base">{domain.name}</CardTitle>
                          <Badge variant="secondary">{(Array.isArray(domain.topics) ? domain.topics : []).length} topics</Badge>
                        </div>
                        <div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
                          <Button variant="ghost" size="sm" onClick={() => aiSuggestMutation.mutate(domain.id)} disabled={aiSuggestMutation.isPending}>
                            <Sparkles className="h-3 w-3 mr-1" /> AI Suggest
                          </Button>
                          <Button variant="ghost" size="sm" onClick={() => { setShowAddTopic(domain.id); setNewTopicName(""); }}>
                            <Plus className="h-3 w-3 mr-1" /> Topic
                          </Button>
                          <Button variant="ghost" size="sm" className="text-destructive" onClick={() => { if (!window.confirm(`Delete domain "${domain.name}"?`)) return; deleteDomainMutation.mutate(domain.id); }}>
                            <Trash2 className="h-3 w-3" />
                          </Button>
                        </div>
                      </CollapsibleTrigger>
                    </CardHeader>
                    <CollapsibleContent>
                      <CardContent className="pt-0">
                        <div className="space-y-2">
                          {showAddTopic === domain.id && (
                            <div className="flex items-center gap-2 p-2 rounded border bg-muted/50">
                              <Input placeholder="Topic name" value={newTopicName} onChange={(e) => setNewTopicName(e.target.value)} className="h-8 text-sm" />
                              <Select value={newTopicDifficulty} onValueChange={setNewTopicDifficulty}>
                                <SelectTrigger className="w-28 h-8"><SelectValue /></SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="easy">Easy</SelectItem>
                                  <SelectItem value="medium">Medium</SelectItem>
                                  <SelectItem value="hard">Hard</SelectItem>
                                </SelectContent>
                              </Select>
                              <Input placeholder="Hrs" type="number" value={newTopicHours} onChange={(e) => setNewTopicHours(e.target.value)} className="w-16 h-8 text-sm" />
                              <Button size="sm" disabled={createTopicMutation.isPending || !newTopicName} onClick={() => createTopicMutation.mutate({ name: newTopicName, domain_id: domain.id, difficulty_level: newTopicDifficulty, estimated_hours: Number(newTopicHours) || 1 })}>Add</Button>
                              <Button size="sm" variant="ghost" onClick={() => setShowAddTopic(null)}><X className="h-3 w-3" /></Button>
                            </div>
                          )}
                          {(Array.isArray(domain.topics) ? domain.topics : []).map(topic => (
                            <div key={topic.id} className="flex items-center justify-between p-2 rounded border hover:bg-accent/50">
                              <div className="flex items-center gap-2">
                                <FileText className="h-3 w-3 text-muted-foreground" />
                                <span className="text-sm">{topic.name}</span>
                                <Badge variant="outline" className="text-xs">{topic.difficulty_level}</Badge>
                                <span className="text-xs text-muted-foreground">{(Array.isArray(topic.objectives) ? topic.objectives : []).length} objectives</span>
                              </div>
                              <div className="flex items-center gap-2">
                                <span className="text-xs text-muted-foreground">~{topic.estimated_hours}h</span>
                                <Button size="sm" variant="ghost" className="text-destructive h-6 w-6 p-0" onClick={() => { if (!window.confirm(`Delete topic "${topic.name}"?`)) return; deleteTopicMutation.mutate(topic.id); }}>
                                  <Trash2 className="h-3 w-3" />
                                </Button>
                              </div>
                            </div>
                          ))}
                          {(Array.isArray(domain.topics) ? domain.topics : []).length === 0 && !showAddTopic && <p className="text-sm text-muted-foreground py-2">No topics in this domain yet.</p>}
                        </div>
                      </CardContent>
                    </CollapsibleContent>
                  </Card>
                </Collapsible>
              ))}
              {(Array.isArray(tree.domains) ? tree.domains : []).length === 0 && <Card><CardContent className="py-8 text-center text-muted-foreground">No domains defined yet for this subject.</CardContent></Card>}
            </div>
          ) : null}
        </div>
      </div>

      <Dialog open={showAddDomain} onOpenChange={setShowAddDomain}>
        <DialogContent>
          <DialogHeader><DialogTitle>Add Domain</DialogTitle></DialogHeader>
          <div className="space-y-2">
            <Label>Domain Name</Label>
            <Input placeholder="e.g. Algebra" value={newDomainName} onChange={(e) => setNewDomainName(e.target.value)} />
          </div>
          <div className="flex justify-end gap-2 pt-2">
            <Button variant="outline" onClick={() => setShowAddDomain(false)}>Cancel</Button>
            <Button disabled={createDomainMutation.isPending || !newDomainName || !selectedSubjectId} onClick={() => createDomainMutation.mutate({ name: newDomainName, subject_id: selectedSubjectId! })}>
              {createDomainMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />} Create
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
