'use client'

/**
 * LeaveTeamDialog — confirm-and-leave modal. The backend enforces the
 * "last owner can't leave" rule (startsim-tsm); this dialog just surfaces
 * the API error inline so the user sees why the action failed.
 *
 * Apps wire `onSubmit` to api.teams.removeMember(team.slug, currentUserId).
 * startsim-o7s.
 */

import * as React from 'react'
import type { TeamLite } from './types'
import {
  LEAVE_DIALOG_DEFAULTS,
  type LeaveTeamDialogClassNames,
} from './leave-team-dialog-default-class-names'

export interface LeaveTeamDialogProps {
  team: TeamLite
  onSubmit?: (team: TeamLite) => Promise<void> | void
  onLeft?: (team: TeamLite) => void
  triggerLabel?: string
  title?: string
  /** Override the confirmation body copy. */
  description?: React.ReactNode
  classNames?: LeaveTeamDialogClassNames
  open?: boolean
  onOpenChange?: (open: boolean) => void
}

export function LeaveTeamDialog({
  team,
  onSubmit,
  onLeft,
  triggerLabel = 'Leave team',
  title,
  description,
  classNames,
  open: controlledOpen,
  onOpenChange,
}: LeaveTeamDialogProps) {
  const cls = { ...LEAVE_DIALOG_DEFAULTS, ...(classNames ?? {}) }
  const [internalOpen, setInternalOpen] = React.useState(false)
  const open = controlledOpen ?? internalOpen
  const setOpen = (next: boolean) => {
    if (controlledOpen === undefined) setInternalOpen(next)
    onOpenChange?.(next)
  }

  const [submitting, setSubmitting] = React.useState(false)
  const [error, setError] = React.useState('')

  function close() {
    setOpen(false)
    setError('')
    setSubmitting(false)
  }

  async function handleConfirm() {
    setError('')
    setSubmitting(true)
    try {
      await onSubmit?.(team)
      onLeft?.(team)
      close()
    } catch (err) {
      // Backend will reject leave when the user is the sole OWNER (startsim-tsm).
      setError(err instanceof Error ? err.message : 'Could not leave team')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <>
      <button
        type="button"
        className={cls.trigger}
        onClick={() => setOpen(true)}
        aria-haspopup="dialog"
      >
        {triggerLabel}
      </button>
      {open && (
        <div className={cls.overlay} role="presentation" onClick={close}>
          <div
            className={cls.panel}
            role="dialog"
            aria-modal="true"
            aria-label={title ?? `Leave ${team.name}`}
            onClick={(e) => e.stopPropagation()}
          >
            <div className={cls.header}>
              <h2 className={cls.title}>{title ?? `Leave ${team.name}`}</h2>
            </div>
            <div className={cls.body}>
              {description ?? (
                <p className={cls.warningText}>
                  You will lose access to <strong>{team.name}</strong>. An owner
                  can re-invite you later. If you&apos;re the only owner you
                  must promote someone else first.
                </p>
              )}
              {error && <p className={cls.errorText} role="alert">{error}</p>}
            </div>
            <div className={cls.footer}>
              <button
                type="button"
                className={cls.cancelButton}
                onClick={close}
                disabled={submitting}
              >
                Cancel
              </button>
              <button
                type="button"
                className={cls.confirmButton}
                onClick={handleConfirm}
                disabled={submitting}
              >
                {submitting ? 'Leaving…' : 'Leave team'}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  )
}
