"use client"

import { useState } from "react"
import { ChevronRight, FileText, Folder, MoreHorizontal, Plus, Trash2 } from "lucide-react"
import { toast } from "sonner"
import { Chapter } from "../types"
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/shared/components/ui/collapsible"
import { Button } from "@/shared/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/components/ui/alert-dialog"
import { cn } from "@/shared/lib/utils"
import { CreateChapterDialog } from "./create-chapter-dialog"
import { deleteChapterAction } from "../actions"

interface ChapterItemProps {
  chapter: Chapter
  level?: number
  selectedId?: string
  onSelect: (chapter: Chapter) => void
  textbookId: string
}

function ChapterItem({ chapter, level = 0, selectedId, onSelect, textbookId }: ChapterItemProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [showCreateDialog, setShowCreateDialog] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [isDeleting, setIsDeleting] = useState(false)
  const hasChildren = chapter.children && chapter.children.length > 0
  const isSelected = chapter.id === selectedId

  const handleDelete = async () => {
    setIsDeleting(true)
    const res = await deleteChapterAction(chapter.id, textbookId)
    setIsDeleting(false)
    if (res.success) {
      toast.success(res.message)
      setShowDeleteDialog(false)
    } else {
      toast.error(res.message)
    }
  }

  return (
    <div className={cn("w-full", level > 0 && "ml-4 border-l pl-2")}>
      <Collapsible open={isOpen} onOpenChange={setIsOpen}>
        <div className={cn(
            "flex items-center group py-1 rounded-md transition-colors",
            isSelected ? "bg-accent text-accent-foreground" : "hover:bg-muted/50"
        )}>
          {hasChildren ? (
            <CollapsibleTrigger asChild>
              <Button
                variant="ghost"
                size="icon"
                className="h-6 w-6 shrink-0 p-0 hover:bg-muted"
                onClick={(e) => e.stopPropagation()} // Prevent selecting parent when toggling
              >
                <ChevronRight
                  className={cn(
                    "h-4 w-4 transition-transform duration-200 text-muted-foreground",
                    isOpen && "rotate-90"
                  )}
                />
                <span className="sr-only">Toggle</span>
              </Button>
            </CollapsibleTrigger>
          ) : (
            <div className="w-6 shrink-0" />
          )}
          
          <div 
            className={cn(
                "flex flex-1 min-w-0 items-center gap-2 px-2 py-1.5 text-sm cursor-pointer",
                level === 0 ? "font-medium" : "text-muted-foreground",
                isSelected && "text-accent-foreground font-medium"
            )}
            onClick={() => onSelect(chapter)}
          >
            {hasChildren ? (
              <Folder className={cn("h-4 w-4", isOpen ? "text-primary" : "text-muted-foreground/70")} />
            ) : (
              <FileText className="h-4 w-4 text-muted-foreground/50" />
            )}
            <span className="truncate flex-1 min-w-0">{chapter.title}</span>
            
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  className="ml-auto h-6 w-6 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity focus:opacity-100"
                  onClick={(e) => e.stopPropagation()}
                >
                  <MoreHorizontal className="h-4 w-4 text-muted-foreground" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem
                  onSelect={() => setShowCreateDialog(true)}
                >
                  <Plus />
                  Add Subchapter
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem variant="destructive" onSelect={() => setShowDeleteDialog(true)}>
                  <Trash2 />
                  Delete
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>

        {hasChildren && (
          <CollapsibleContent className="overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down">
             <div className="pt-1">
              {chapter.children!.map((child) => (
                <ChapterItem 
                    key={child.id} 
                    chapter={child} 
                    level={level + 1} 
                    selectedId={selectedId}
                    onSelect={onSelect}
                    textbookId={textbookId}
                />
              ))}
            </div>
          </CollapsibleContent>
        )}
      </Collapsible>

      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete chapter?</AlertDialogTitle>
            <AlertDialogDescription>
              This will delete this chapter and all its subchapters and linked knowledge points.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              onClick={handleDelete}
              disabled={isDeleting}
            >
              {isDeleting ? "Deleting..." : "Delete"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <CreateChapterDialog
        textbookId={textbookId}
        parentId={chapter.id}
        trigger={null}
        open={showCreateDialog}
        onOpenChange={setShowCreateDialog}
      />
    </div>
  )
}

export function ChapterSidebarList({ 
    chapters, 
    selectedChapterId, 
    onSelectChapter,
    textbookId,
}: { 
    chapters: Chapter[], 
    selectedChapterId?: string,
    onSelectChapter: (chapter: Chapter) => void 
    textbookId: string
}) {
  return (
    <div className="space-y-1">
      {chapters.map((chapter) => (
        <ChapterItem 
            key={chapter.id} 
            chapter={chapter} 
            selectedId={selectedChapterId}
            onSelect={onSelectChapter}
            textbookId={textbookId}
        />
      ))}
    </div>
  )
}
