import { useState } from 'react'
import { Alert } from '@/components/ui/Alert'
import { Button } from '@/components/ui/Button'
import { Modal } from '@/components/ui/Modal'
import { errorMessage } from '@/lib/api'
import { formatQuantity, useDeleteSeedLot, type SeedLot } from '@/lib/seedLots'

/**
 * Retire a lot. Worth confirming because it's the one place cost and germination
 * data lives — and worth saying plainly that the plantings survive it, since
 * "will this wipe my garden" is the reasonable fear.
 */
export function DeleteSeedLotModal({ lot, onClose }: { lot: SeedLot; onClose: () => void }) {
  const del = useDeleteSeedLot()
  const [error, setError] = useState<string | null>(null)

  return (
    <Modal title="Retire this seed lot?" onClose={onClose} busy={del.isPending}>
      <div className="flex flex-col gap-3">
        <p className="text-sm text-fg">
          {formatQuantity(lot.quantity)} {lot.unit}
          {lot.vendor ? ` from ${lot.vendor}` : ''}
          {lot.packedForYear != null ? `, packed for ${lot.packedForYear}` : ''}.
        </p>
        <p className="text-sm text-muted">
          Anything planted from it stays exactly where it is — it just stops being attributed to this purchase.
        </p>
        {error && <Alert>{error}</Alert>}
        <div className="mt-1 flex justify-end gap-2">
          <Button type="button" variant="ghost" onClick={onClose} disabled={del.isPending}>
            Cancel
          </Button>
          <Button
            type="button"
            variant="danger"
            disabled={del.isPending}
            onClick={() =>
              del.mutate(lot.id, {
                onSuccess: onClose,
                onError: (err) => setError(errorMessage(err, 'Could not retire the lot.')),
              })
            }
          >
            {del.isPending ? 'Retiring…' : 'Retire lot'}
          </Button>
        </div>
      </div>
    </Modal>
  )
}
