'use client'

import { useDeleteAlbumImage } from '@/hooks/aiUser'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '../ui/alert-dialog'
import { Button } from '../ui/button'
import { useState } from 'react'

const AlbumDeleteAlert = ({
  aiId,
  albumId,
  isDefaultImage,
  onDeleted,
  children,
}: {
  aiId: number
  albumId: number
  isDefaultImage: boolean
  onDeleted?: () => void
  children: React.ReactNode
}) => {
  const [isOpen, setIsOpen] = useState(false)
  const deleteMutation = useDeleteAlbumImage()

  const handleDelete = async () => {
    try {
      await deleteMutation.mutateAsync({ aiId, albumId })
      onDeleted?.()
      setIsOpen(false)
    } catch (error) {
      console.error(error)
    } finally {
      setIsOpen(false)
    }
  }

  return (
    <AlertDialog open={isOpen} onOpenChange={setIsOpen}>
      <AlertDialogTrigger asChild>{children}</AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Delete Image</AlertDialogTitle>
        </AlertDialogHeader>
        <AlertDialogDescription>
          {isDefaultImage
            ? 'The default cover image cannot be deleted. It will appear as your profile header, card cover, and chat background.'
            : `Once deleted, the image cannot be restored. Users who have already unlocked this image will still be able to view it in the character's album.`}
        </AlertDialogDescription>
        {isDefaultImage ? (
          <AlertDialogFooter>
            <AlertDialogAction onClick={() => setIsOpen(false)}>Got it</AlertDialogAction>
          </AlertDialogFooter>
        ) : (
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <Button variant="primary" loading={deleteMutation.isPending} onClick={handleDelete}>
              Delete
            </Button>
          </AlertDialogFooter>
        )}
      </AlertDialogContent>
    </AlertDialog>
  )
}

export default AlbumDeleteAlert
