"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { MoreHorizontal, Eye, Pencil, Trash, Archive, UploadCloud, Undo2, Copy } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/shared/components/ui/button"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/components/ui/alert-dialog"
import {
  Dialog,
  DialogContent,
  DialogTitle,
} from "@/shared/components/ui/dialog"

import { deleteExamAction, duplicateExamAction, updateExamAction, getExamPreviewAction } from "../actions"
import { Exam } from "../types"
import { ExamPaperPreview } from "./assembly/exam-paper-preview"
import type { ExamNode } from "./assembly/selected-question-list"
import type { Question } from "@/modules/questions/types"

interface ExamActionsProps {
  exam: Exam
}

export function ExamActions({ exam }: ExamActionsProps) {
  const router = useRouter()
  const [showViewDialog, setShowViewDialog] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [isWorking, setIsWorking] = useState(false)
  const [previewNodes, setPreviewNodes] = useState<ExamNode[] | null>(null)
  const [loadingPreview, setLoadingPreview] = useState(false)

  const handleView = async () => {
    setLoadingPreview(true)
    setShowViewDialog(true)
    try {
      const result = await getExamPreviewAction(exam.id)
      if (result.success && result.data) {
        const { structure, questions } = result.data
        const questionById = new Map<string, Question>()
        for (const q of questions) questionById.set(q.id, q as unknown as Question)

        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const hydrate = (nodes: any[]): ExamNode[] => {
            return nodes.map((node) => {
                if (node.type === "question") {
                    const q = node.questionId ? questionById.get(node.questionId) : undefined
                    return { ...node, question: q }
                }
                if (node.type === "group") {
                    return { ...node, children: hydrate(node.children || []) }
                }
                return node
            })
        }
        
        const nodes = Array.isArray(structure) ? hydrate(structure) : []
        setPreviewNodes(nodes)
      } else {
        toast.error("Failed to load exam preview")
        setShowViewDialog(false)
      }
    } catch {
      toast.error("Failed to load exam preview")
      setShowViewDialog(false)
    } finally {
      setLoadingPreview(false)
    }
  }

  const copyId = () => {
    navigator.clipboard.writeText(exam.id)
    toast.success("Exam ID copied to clipboard")
  }

  const setStatus = async (status: Exam["status"]) => {
    setIsWorking(true)
    try {
      const formData = new FormData()
      formData.set("examId", exam.id)
      formData.set("status", status)
      const result = await updateExamAction(null, formData)
      if (result.success) {
        toast.success(status === "published" ? "Exam published" : status === "archived" ? "Exam archived" : "Exam moved to draft")
        router.refresh()
      } else {
        toast.error(result.message || "Failed to update exam")
      }
    } catch {
      toast.error("Failed to update exam")
    } finally {
      setIsWorking(false)
    }
  }

  const duplicateExam = async () => {
    setIsWorking(true)
    try {
      const formData = new FormData()
      formData.set("examId", exam.id)
      const result = await duplicateExamAction(null, formData)
      if (result.success && result.data) {
        toast.success("Exam duplicated")
        router.push(`/teacher/exams/${result.data}/build`)
        router.refresh()
      } else {
        toast.error(result.message || "Failed to duplicate exam")
      }
    } catch {
      toast.error("Failed to duplicate exam")
    } finally {
      setIsWorking(false)
    }
  }

  const handleDelete = async () => {
    setIsWorking(true)
    try {
      const formData = new FormData()
      formData.set("examId", exam.id)
      const result = await deleteExamAction(null, formData)
      if (result.success) {
        toast.success("Exam deleted successfully")
        setShowDeleteDialog(false)
        router.refresh()
      } else {
        toast.error(result.message || "Failed to delete exam")
      }
    } catch {
      toast.error("Failed to delete exam")
    } finally {
      setIsWorking(false)
    }
  }

  return (
    <>
      <div className="flex items-center gap-1">
        <Button
          variant="ghost"
          size="icon"
          className="h-8 w-8 text-muted-foreground hover:text-foreground"
          onClick={(e) => {
            e.stopPropagation()
            handleView()
          }}
          title="Preview Exam"
          aria-label="Preview exam"
        >
          <Eye className="h-4 w-4" />
        </Button>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" className="h-8 w-8 p-0" aria-label="Open menu">
              <span className="sr-only">Open menu</span>
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuLabel>Actions</DropdownMenuLabel>
            <DropdownMenuItem onClick={copyId}>
              <Copy className="mr-2 h-4 w-4" /> Copy ID
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem onClick={() => router.push(`/teacher/exams/${exam.id}/build`)}>
              <Pencil className="mr-2 h-4 w-4" /> Edit
            </DropdownMenuItem>
          <DropdownMenuItem onClick={() => router.push(`/teacher/exams/${exam.id}/build`)}>
            <MoreHorizontal className="mr-2 h-4 w-4" /> Build
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <DropdownMenuItem onClick={duplicateExam} disabled={isWorking}>
            <Copy className="mr-2 h-4 w-4" /> Duplicate
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <DropdownMenuItem
            onClick={() => setStatus("published")}
            disabled={isWorking || exam.status === "published"}
          >
            <UploadCloud className="mr-2 h-4 w-4" /> Publish
          </DropdownMenuItem>
          <DropdownMenuItem
            onClick={() => setStatus("draft")}
            disabled={isWorking || exam.status === "draft"}
          >
            <Undo2 className="mr-2 h-4 w-4" /> Move to Draft
          </DropdownMenuItem>
          <DropdownMenuItem
            onClick={() => setStatus("archived")}
            disabled={isWorking || exam.status === "archived"}
          >
            <Archive className="mr-2 h-4 w-4" /> Archive
          </DropdownMenuItem>
          <DropdownMenuItem
            className="text-destructive focus:text-destructive"
            onClick={() => setShowDeleteDialog(true)}
            disabled={isWorking}
          >
            <Trash className="mr-2 h-4 w-4" /> Delete
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
      </div>
      
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
            <AlertDialogDescription>
              This action cannot be undone. This will permanently delete the exam
              &quot;{exam.title}&quot; and remove all associated data.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              onClick={(e) => {
                e.preventDefault()
                handleDelete()
              }}
              disabled={isWorking}
            >
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <Dialog open={showViewDialog} onOpenChange={setShowViewDialog}>
        <DialogContent className="max-w-4xl h-[90vh] flex flex-col p-0 gap-0">
            <div className="p-4 border-b shrink-0 flex items-center justify-between">
               <DialogTitle className="text-lg font-semibold tracking-tight">{exam.title}</DialogTitle>
            </div>
            <ScrollArea className="flex-1">
                {loadingPreview ? (
                    <div className="py-20 text-center text-muted-foreground">Loading preview...</div>
                ) : previewNodes && previewNodes.length > 0 ? (
                    <div className="max-w-3xl mx-auto py-8 px-6">
                        <ExamPaperPreview 
                            title={exam.title}
                            subject={exam.subject}
                            grade={exam.grade}
                            durationMin={exam.durationMin}
                            totalScore={exam.totalScore}
                            nodes={previewNodes}
                        />
                    </div>
                ) : (
                    <div className="py-20 text-center text-muted-foreground">
                        No questions in this exam.
                    </div>
                )}
            </ScrollArea>
        </DialogContent>
      </Dialog>
    </>
  )
}
