'use client'

import { useState } from 'react'
import { Dialog, DialogActions, DialogContent, DialogTitle, Button, Typography, CircularProgress } from '@mui/material'
import { toast } from 'react-toastify'
import { useDeleteCategory } from '@/@core/hooks/data/categories/useUpdateAndDeleteCategory'

type Props = {
  open: boolean
  handleClose: () => void
  categoryId?: string
  onDeleted?: () => void
}

const DeleteCategoryDialog = ({ open, handleClose, categoryId, onDeleted }: Props) => {
  const deleteCategory = useDeleteCategory()
  const [loading, setLoading] = useState(false)

  const handleDelete = async () => {
    if (!categoryId) return
    setLoading(true)
    try {
      const res = await deleteCategory.mutateAsync(categoryId)

      const messages = Array.isArray((res as any)?.messages) ? (res as any)?.messages : (res as any)?.messages

      if (messages) {
        if (Array.isArray(messages)) {
          messages.filter(Boolean).forEach((m: string) => toast.success(m))
        } else {
          toast.success(messages as string)
        }
      }

      onDeleted?.()
      handleClose()
    } catch (error: any) {
      const errMessages = Array.isArray(error?.response?.data?.messages)
        ? error?.response?.data?.messages
        : error?.response?.data?.messages

      if (errMessages) {
        if (Array.isArray(errMessages)) {
          errMessages.filter(Boolean).forEach((m: string) => toast.error(m))
        } else {
          toast.error(errMessages as string)
        }
      }
    } finally {
      setLoading(false)
    }
  }

  return (
    <Dialog open={open} onClose={handleClose}>
      <DialogTitle>تأكيد الحذف</DialogTitle>
      <DialogContent>
        <Typography>هل أنت متأكد أنك تريد حذف هذه الفئة؟ لا يمكن التراجع بعد ذلك.</Typography>
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color='secondary' variant='tonal' disabled={loading}>
          إلغاء
        </Button>
        <Button color='error' variant='contained' onClick={handleDelete} disabled={loading}>
          {loading ? <CircularProgress size={24} /> : 'حذف'}
        </Button>
      </DialogActions>
    </Dialog>
  )
}

export default DeleteCategoryDialog
