"use client"

import type React from "react"

import { useCallback, useState } from "react"
import { enqueueSnackbar } from "notistack"

interface ConfirmDialogState {
  open: boolean
  tabId: number | null
  tabLabel: string
}

interface UseConfirmDialogReturn {
  confirmDialog: ConfirmDialogState
  handleTabCloseRequest: (
    event: React.MouseEvent,
    tabId: number,
    tabLabel?: string,
    validationFn?: (tabId: number) => { canDelete: boolean; message?: string },
  ) => void
  handleConfirmTabClose: (onConfirm: (tabId: number) => void) => void
  handleCancelTabClose: () => void
}

export function useConfirmDialog(): UseConfirmDialogReturn {
  const [confirmDialog, setConfirmDialog] = useState<ConfirmDialogState>({
    open: false,
    tabId: null,
    tabLabel: "",
  })

  const handleTabCloseRequest = useCallback(
    (
      event: React.MouseEvent,
      tabId: number,
      tabLabel?: string,
      validationFn?: (tabId: number) => { canDelete: boolean; message?: string },
    ) => {
      event.stopPropagation()

      if (validationFn) {
        const validation = validationFn(tabId)
        if (!validation.canDelete) {
          enqueueSnackbar(validation.message || "Impossible de supprimer cet élément", {
            variant: "warning",
          })
          return
        }
      }

      const label = tabLabel || `Adresse ${tabId + 1}`
      setConfirmDialog({
        open: true,
        tabId,
        tabLabel: label,
      })
    },
    [],
  )

  const handleConfirmTabClose = useCallback(
    (onConfirm: (tabId: number) => void) => {
      if (confirmDialog.tabId !== null) {
        onConfirm(confirmDialog.tabId)
      }
      setConfirmDialog({
        open: false,
        tabId: null,
        tabLabel: "",
      })
    },
    [confirmDialog.tabId],
  )

  const handleCancelTabClose = useCallback(() => {
    setConfirmDialog({
      open: false,
      tabId: null,
      tabLabel: "",
    })
  }, [])

  return {
    confirmDialog,
    handleTabCloseRequest,
    handleConfirmTabClose,
    handleCancelTabClose,
  }
}
