import { ConfirmModal } from '@/components/ui/ConfirmModal'
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)
  return (
    <ConfirmModal
      title="Leave garden"
      confirmLabel="Leave"
      busyLabel="Leaving…"
      confirmDisabled={!me.data}
      errorFallback="Could not leave the garden."
      onConfirm={async () => {
        // The button is disabled without a current user; throw rather than
        // silently resolve (which would close the dialog as if it had worked) if
        // that guard ever drifts.
        if (!me.data) throw new Error('Not signed in.')
        await remove.mutateAsync(me.data.id)
      }}
      onClose={onClose}
    >
      <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>
    </ConfirmModal>
  )
}
