import { useState } from 'react'
import { Modal } from '@/components/ui/Modal'
import { Alert } from '@/components/ui/Alert'
import { Button } from '@/components/ui/Button'
import { errorMessage } from '@/lib/api'
import { useDeleteGarden, type Garden } from '@/lib/gardens'

/** Confirmation dialog for deleting a garden (and everything in it). */
export function DeleteGardenModal({ garden, onClose }: { garden: Garden; onClose: () => void }) {
  const deletion = useDeleteGarden()
  const [error, setError] = useState<string | null>(null)

  async function onConfirm() {
    setError(null)
    try {
      await deletion.mutateAsync(garden.id)
      onClose()
    } catch (err) {
      setError(errorMessage(err, 'Could not delete the garden.'))
    }
  }

  return (
    <Modal title="Delete garden" onClose={onClose} busy={deletion.isPending}>
      <div className="flex flex-col gap-4">
        <p className="text-sm text-muted">
          Delete <span className="font-medium text-fg">{garden.name}</span> and everything planned in it?
          This can't be undone.
        </p>
        {error && <Alert>{error}</Alert>}
        <div className="flex justify-end gap-2">
          <Button type="button" variant="ghost" onClick={onClose} disabled={deletion.isPending}>
            Cancel
          </Button>
          <Button type="button" variant="danger" onClick={onConfirm} disabled={deletion.isPending}>
            {deletion.isPending ? 'Deleting…' : 'Delete'}
          </Button>
        </div>
      </div>
    </Modal>
  )
}
