import { useEffect } from "react";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { useQuery } from "@tanstack/react-query";
import { taxonomyService } from "@/services/taxonomy.service";
import { lmsService } from "@/services/lms.service";

interface TaxonomyCascadeProps {
  subjectId: string;
  onSubjectChange: (id: string) => void;
  domainId: string;
  onDomainChange: (id: string) => void;
  topicIds: number[];
  onTopicIdsChange: (ids: number[]) => void;
  objectiveIds: number[];
  onObjectiveIdsChange: (ids: number[]) => void;
}

export function TaxonomyCascade({
  subjectId, onSubjectChange,
  domainId, onDomainChange,
  topicIds, onTopicIdsChange,
  objectiveIds, onObjectiveIdsChange,
}: TaxonomyCascadeProps) {
  const { data: subjects } = useQuery({
    queryKey: ["taxonomy", "subjects"],
    queryFn: () => taxonomyService.listSubjects(),
  });

  const numericSubjectId = subjectId !== "none" ? Number(subjectId) : undefined;
  const numericDomainId = domainId !== "none" ? Number(domainId) : undefined;

  const { data: domains } = useQuery({
    queryKey: ["taxonomy", "domains", numericSubjectId],
    queryFn: () => taxonomyService.listDomains({ subject_id: numericSubjectId }),
    enabled: !!numericSubjectId,
  });

  const { data: topics } = useQuery({
    queryKey: ["taxonomy", "topics", numericDomainId],
    queryFn: () => taxonomyService.listTopics({ domain_id: numericDomainId }),
    enabled: !!numericDomainId,
  });

  const { data: objectivesData } = useQuery({
    queryKey: ["learning-objectives", topicIds],
    queryFn: () => lmsService.listLearningObjectives({ topic_ids: topicIds.join(",") }),
    enabled: topicIds.length > 0,
  });
  const objectives = objectivesData?.items ?? [];

  useEffect(() => {
    if (subjectId === "none") {
      if (domainId !== "none") onDomainChange("none");
      if (topicIds.length > 0) onTopicIdsChange([]);
      if (objectiveIds.length > 0) onObjectiveIdsChange([]);
    }
  }, [subjectId]);

  useEffect(() => {
    if (domainId === "none") {
      if (topicIds.length > 0) onTopicIdsChange([]);
      if (objectiveIds.length > 0) onObjectiveIdsChange([]);
    }
  }, [domainId]);

  const toggleTopic = (id: number) => {
    const next = topicIds.includes(id) ? topicIds.filter(t => t !== id) : [...topicIds, id];
    onTopicIdsChange(next);
    if (next.length === 0 && objectiveIds.length > 0) onObjectiveIdsChange([]);
  };

  const toggleObjective = (id: number) => {
    onObjectiveIdsChange(
      objectiveIds.includes(id) ? objectiveIds.filter(o => o !== id) : [...objectiveIds, id],
    );
  };

  return (
    <div className="space-y-3">
      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <Label className="text-xs">Subject</Label>
          <Select value={subjectId} onValueChange={(v) => { onSubjectChange(v); if (v === "none") { onDomainChange("none"); } }}>
            <SelectTrigger className="h-8 text-sm"><SelectValue placeholder="Select subject" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="none">None</SelectItem>
              {(subjects ?? []).map(s => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
            </SelectContent>
          </Select>
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs">Domain</Label>
          <Select value={domainId} onValueChange={onDomainChange} disabled={!numericSubjectId}>
            <SelectTrigger className="h-8 text-sm"><SelectValue placeholder={numericSubjectId ? "Select domain" : "Select subject first"} /></SelectTrigger>
            <SelectContent>
              <SelectItem value="none">None</SelectItem>
              {(domains ?? []).map(d => <SelectItem key={d.id} value={String(d.id)}>{d.name}</SelectItem>)}
            </SelectContent>
          </Select>
        </div>
      </div>

      {numericDomainId && (topics ?? []).length > 0 && (
        <div className="space-y-1.5">
          <Label className="text-xs">Topics</Label>
          <div className="flex flex-wrap gap-1.5 p-2 rounded border bg-muted/30 max-h-[100px] overflow-y-auto">
            {(topics ?? []).map(t => (
              <Badge
                key={t.id}
                variant={topicIds.includes(t.id) ? "default" : "outline"}
                className="cursor-pointer select-none text-xs"
                onClick={() => toggleTopic(t.id)}
              >
                {t.name}
              </Badge>
            ))}
          </div>
        </div>
      )}

      {topicIds.length > 0 && objectives.length > 0 && (
        <div className="space-y-1.5">
          <Label className="text-xs">Learning Objectives</Label>
          <div className="space-y-1 p-2 rounded border bg-muted/30 max-h-[100px] overflow-y-auto">
            {objectives.map(o => (
              <label key={o.id} className="flex items-center gap-2 text-xs cursor-pointer">
                <Checkbox
                  checked={objectiveIds.includes(o.id)}
                  onCheckedChange={() => toggleObjective(o.id)}
                />
                <span>{o.name}</span>
                {o.bloom_level && <Badge variant="outline" className="text-[10px] h-4">{o.bloom_level}</Badge>}
              </label>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
