"use client"

import { useState } from "react"
import { useTranslations } from "next-intl"
import { MoreHorizontal, Pencil, Trash, Eye, Copy } from "lucide-react"
import { useRouter } from "next/navigation"

import { Button } from "@/shared/components/ui/button"
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,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/shared/components/ui/dialog"

import type { Question } from "../types"
import { deleteQuestionAction } from "../actions"
import { CreateQuestionDialog } from "./create-question-dialog"
import { QuestionContentRenderer } from "./question-content-renderer"
import { usePermission } from "@/shared/hooks/use-permission"
import { Permissions } from "@/shared/types/permissions"
import { toast } from "sonner"

interface QuestionActionsProps {
  question: Question
}

export function QuestionActions({ question }: QuestionActionsProps): React.ReactNode {
  const t = useTranslations("questions")
  const router = useRouter()
  const { hasPermission } = usePermission()
  const [showEditDialog, setShowEditDialog] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [showViewDialog, setShowViewDialog] = useState(false)
  const [isDeleting, setIsDeleting] = useState(false)

  const canEdit = hasPermission(Permissions.QUESTION_UPDATE)
  const canDelete = hasPermission(Permissions.QUESTION_DELETE)

  const copyId = (): void => {
    try {
      navigator.clipboard.writeText(question.id)
      toast.success(t("actions.copyIdSuccess"))
    } catch (e) {
      console.error("Failed to copy question ID to clipboard", e)
      toast.error(t("actions.copyIdFailed"))
    }
  }

  const handleDelete = async (): Promise<void> => {
    setIsDeleting(true)
    try {
      const fd = new FormData()
      fd.set("questionId", question.id)
      const res = await deleteQuestionAction(undefined, fd)
      if (res.success) {
        toast.success(t("actions.deleteSuccess"))
        setShowDeleteDialog(false)
        router.refresh()
      } else {
        toast.error(res.message || t("actions.deleteFailed"))
      }
    } catch (e) {
      console.error("Failed to delete question", e)
      toast.error(t("actions.deleteFailed"))
    } finally {
      setIsDeleting(false)
    }
  }

  const typeLabel = t(`type.${question.type}`)

  return (
    <>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="ghost" className="h-8 w-8 p-0" aria-label={t("actions.menuLabel")}>
            <span className="sr-only">{t("actions.menuLabel")}</span>
            <MoreHorizontal className="h-4 w-4" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <DropdownMenuLabel>{t("actions.actions")}</DropdownMenuLabel>
          <DropdownMenuItem onClick={copyId}>
            <Copy className="mr-2 h-4 w-4" /> {t("actions.copyId")}
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <DropdownMenuItem onClick={() => setShowViewDialog(true)}>
            <Eye className="mr-2 h-4 w-4" /> {t("actions.viewDetails")}
          </DropdownMenuItem>
          {canEdit && (
            <DropdownMenuItem onClick={() => setShowEditDialog(true)}>
              <Pencil className="mr-2 h-4 w-4" /> {t("actions.edit")}
            </DropdownMenuItem>
          )}
          {canDelete && (
            <DropdownMenuItem
              className="text-destructive focus:text-destructive"
              onClick={() => setShowDeleteDialog(true)}
            >
              <Trash className="mr-2 h-4 w-4" /> {t("actions.delete")}
            </DropdownMenuItem>
          )}
        </DropdownMenuContent>
      </DropdownMenu>

      {canEdit && (
        <CreateQuestionDialog
          open={showEditDialog}
          onOpenChange={setShowEditDialog}
          initialData={question}
        />
      )}

      {canDelete && (
        <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>{t("actions.deleteConfirmTitle")}</AlertDialogTitle>
              <AlertDialogDescription>
                {t("actions.deleteConfirmDesc")}
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>{t("actions.deleteConfirmCancel")}</AlertDialogCancel>
              <AlertDialogAction
                onClick={(e) => {
                  e.preventDefault()
                  handleDelete()
                }}
                className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                disabled={isDeleting}
              >
                {isDeleting ? t("actions.deleting") : t("actions.deleteConfirmAction")}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      )}

      <Dialog open={showViewDialog} onOpenChange={setShowViewDialog}>
        <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
            <DialogHeader>
                <DialogTitle>{t("actions.detailsTitle")}</DialogTitle>
                <DialogDescription>{t("actions.detailsId", { id: question.id })}</DialogDescription>
            </DialogHeader>
            <div className="grid gap-4 py-4">
                <div className="grid grid-cols-4 items-center gap-4">
                    <span className="font-medium">{t("actions.detailsType")}</span>
                    <span className="col-span-3">{typeLabel}</span>
                </div>
                <div className="grid grid-cols-4 items-center gap-4">
                    <span className="font-medium">{t("actions.detailsDifficulty")}</span>
                    <span className="col-span-3">{question.difficulty}</span>
                </div>
                <div className="grid grid-cols-4 items-start gap-4">
                    <span className="font-medium pt-1">{t("actions.detailsContent")}</span>
                    <div className="col-span-3 rounded-md bg-muted p-3">
                        <QuestionContentRenderer question={question} showAnswer />
                    </div>
                </div>
                 {question.author && (
                     <div className="grid grid-cols-4 items-center gap-4">
                        <span className="font-medium">{t("actions.detailsAuthor")}</span>
                        <span className="col-span-3">{question.author.name || t("actions.detailsUnknown")}</span>
                    </div>
                 )}
                 {question.knowledgePoints && question.knowledgePoints.length > 0 && (
                     <div className="grid grid-cols-4 items-center gap-4">
                        <span className="font-medium">{t("actions.detailsTags")}</span>
                        <div className="col-span-3 flex flex-wrap gap-1">
                            {question.knowledgePoints.map(kp => (
                                <span key={kp.id} className="rounded-full bg-secondary px-2 py-0.5 text-xs text-secondary-foreground">
                                    {kp.name}
                                </span>
                            ))}
                        </div>
                    </div>
                 )}
            </div>
        </DialogContent>
      </Dialog>
    </>
  )
}
