"use client"

import * as React from "react"
import { Loader, Trash } from "lucide-react"
import { toast } from "sonner"
import { useParams } from "next/navigation"
import { useTranslation } from "@/i18n/client"

import { useMediaQuery } from "@/hooks/use-media-query"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  Drawer,
  DrawerClose,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHeader,
  DrawerTitle,
  DrawerTrigger,
} from "@/components/ui/drawer"

import { deleteFormDataByTags } from "@/lib/forms/services"

interface GenericData {
  [key: string]: any
  TAG_NO?: string
}

interface DeleteFormDataDialogProps
  extends React.ComponentPropsWithoutRef<typeof Dialog> {
  formData: GenericData[]
  formCode: string
  contractItemId: number
  projectId?: number
  showTrigger?: boolean
  onSuccess?: () => void
  triggerVariant?: "default" | "destructive" | "outline" | "secondary" | "ghost" | "link"
}

export function DeleteFormDataDialog({
  formData,
  formCode,
  contractItemId,
  projectId,
  showTrigger = true,
  onSuccess,
  triggerVariant = "outline",
  ...props
}: DeleteFormDataDialogProps) {
  const [isDeletePending, startDeleteTransition] = React.useTransition()
  const isDesktop = useMediaQuery("(min-width: 640px)")
  
  const params = useParams();
  const lng = (params?.lng as string) || "ko";
  const { t } = useTranslation(lng, "engineering");

  // TAG_NO가 있는 항목들만 필터링
  const validItems = formData.filter(item => item.TAG_IDX?.trim())
  const tagIdxs = validItems.map(item => item.TAG_IDX).filter(Boolean) as string[]

  function onDelete() {
    startDeleteTransition(async () => {
      if (tagIdxs.length === 0) {
        toast.error(t("delete.noValidItems"))
        return
      }

      const result = await deleteFormDataByTags({
        formCode,
        contractItemId,
        tagIdxs,
        projectId,
      })

      if (result.error) {
        toast.error(result.error)
        return
      }

      props.onOpenChange?.(false)
      
      // 성공 메시지 (개수는 같을 것으로 예상)
      const deletedCount = result.deletedCount || 0
      const deletedTagsCount = result.deletedTagsCount || 0
      
      // SEDP 삭제 결과도 포함
      if (result.sedpDeleteSuccess) {
        console.log("SEDP에서도 성공적으로 삭제되었습니다.")
      } else if (result.sedpDeleteError) {
        console.warn("SEDP 삭제 실패:", result.sedpDeleteError)
        toast.warning(`로컬 삭제는 성공했으나 SEDP 삭제 실패: ${result.sedpDeleteError}`)
      }
      
      if (deletedCount !== deletedTagsCount) {
        // 데이터 불일치 경고
        console.warn(`Data inconsistency: FormEntries deleted: ${deletedCount}, Tags deleted: ${deletedTagsCount}`)
        toast.error(
          t("delete.dataInconsistency", { deletedCount, deletedTagsCount })
        )
      } else {
        // 정상적인 삭제 완료
        const successMessage = result.sedpDeleteSuccess 
          ? t("delete.successMessage", { 
              count: deletedCount,
              items: deletedCount === 1 ? t("delete.item") : t("delete.items")
            }) + " (SEDP 포함)"
          : t("delete.successMessage", { 
              count: deletedCount,
              items: deletedCount === 1 ? t("delete.item") : t("delete.items")
            })
        
        toast.success(successMessage)
      }
      
      onSuccess?.()
    })
  }

  const itemCount = tagIdxs.length
  const hasValidItems = itemCount > 0

  if (isDesktop) {
    return (
      <Dialog {...props}>
        {showTrigger ? (
          <DialogTrigger asChild>
            <Button 
              variant={triggerVariant} 
              size="sm"
              disabled={!hasValidItems}
            >
              <Trash className="mr-2 size-4" aria-hidden="true" />
              {t("buttons.delete")} ({itemCount})
            </Button>
          </DialogTrigger>
        ) : null}
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t("delete.confirmTitle")}</DialogTitle>
            <DialogDescription>
              {t("delete.confirmDescription", { 
                count: itemCount,
                items: itemCount === 1 ? t("delete.item") : t("delete.items")
              })}
              {itemCount > 0 && (
                <>
                  <br />
                  <br />
                  <span className="text-sm text-muted-foreground">
                    {t("delete.tagNumbers")}: {tagIdxs.slice(0, 3).join(", ")}
                    {tagIdxs.length > 3 && t("delete.andMore", { count: tagIdxs.length - 3 })}
                  </span>
                </>
              )}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="gap-2 sm:space-x-0">
            <DialogClose asChild>
              <Button variant="outline">{t("buttons.cancel")}</Button>
            </DialogClose>
            <Button
              aria-label={t("delete.deleteButtonLabel")}
              variant="destructive"
              onClick={onDelete}
              disabled={isDeletePending || !hasValidItems}
            >
              {isDeletePending && (
                <Loader
                  className="mr-2 size-4 animate-spin"
                  aria-hidden="true"
                />
              )}
              {t("buttons.delete")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    )
  }

  return (
    <Drawer {...props}>
      {showTrigger ? (
        <DrawerTrigger asChild>
          <Button 
            variant={triggerVariant} 
            size="sm"
            disabled={!hasValidItems}
          >
            <Trash className="mr-2 size-4" aria-hidden="true" />
            {t("buttons.delete")} ({itemCount})
          </Button>
        </DrawerTrigger>
      ) : null}
      <DrawerContent>
        <DrawerHeader>
          <DrawerTitle>{t("delete.confirmTitle")}</DrawerTitle>
          <DrawerDescription>
            {t("delete.confirmDescription", { 
              count: itemCount,
              items: itemCount === 1 ? t("delete.item") : t("delete.items")
            })}
            {itemCount > 0 && (
              <>
                <br />
                <br />
                <span className="text-sm text-muted-foreground">
                  {t("delete.tagNumbers")}: {tagIdxs.slice(0, 3).join(", ")}
                  {tagIdxs.length > 3 && t("delete.andMore", { count: tagIdxs.length - 3 })}
                </span>
              </>
            )}
          </DrawerDescription>
        </DrawerHeader>
        <DrawerFooter className="gap-2 sm:space-x-0">
          <DrawerClose asChild>
            <Button variant="outline">{t("buttons.cancel")}</Button>
          </DrawerClose>
          <Button
            aria-label={t("delete.deleteButtonLabel")}
            variant="destructive"
            onClick={onDelete}
            disabled={isDeletePending || !hasValidItems}
          >
            {isDeletePending && (
              <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" />
            )}
            {t("buttons.delete")}
          </Button>
        </DrawerFooter>
      </DrawerContent>
    </Drawer>
  )
}