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 { useMe } from '@/lib/auth'
import type { Garden } from '@/lib/gardens'
import { useRemoveShare } from '@/lib/shares'

/** Confirmation for a recipient leaving a garden shared with them (removes their
 *  own share). */
export function LeaveGardenModal({ garden, onClose }: { garden: Garden; onClose: () => void }) {
  const me = useMe()
  const remove = useRemoveShare(garden.id)
  const [error, setError] = useState<string | null>(null)

  async function onConfirm() {
    if (!me.data) return
    setError(null)
    try {
      await remove.mutateAsync(me.data.id)
      onClose()
    } catch (err) {
      setError(errorMessage(err, 'Could not leave the garden.'))
    }
  }

  return (
    <Modal title="Leave garden" onClose={onClose} busy={remove.isPending}>
      <div className="flex flex-col gap-4">
        <p className="text-sm text-muted">
          Leave <span className="font-medium text-fg">{garden.name}</span>? You'll lose access until the owner
          shares it with you again.
        </p>
        {error && <Alert>{error}</Alert>}
        <div className="flex justify-end gap-2">
          <Button type="button" variant="ghost" onClick={onClose} disabled={remove.isPending}>
            Cancel
          </Button>
          <Button type="button" variant="danger" onClick={onConfirm} disabled={remove.isPending || !me.data}>
            {remove.isPending ? 'Leaving…' : 'Leave'}
          </Button>
        </div>
      </div>
    </Modal>
  )
}
