import { useEffect, useState } from 'react'
import type { WrapperRateLimit } from './WrapperCapacity'
import { LinkButton } from './LinkButton'
import { Select } from './Select'

type ResolveKind = 'wait' | 'retry' | 'switch'

export function RateLimitDialog(props: {
  limit: WrapperRateLimit | null
  wrapper: string
  accounts: Array<{ slug: string; health: 'ready' | 'limited' | 'cooling'; note?: string }> | null
  open: boolean
  onClose(): void
  onResolve(choice: { kind: 'wait' | 'retry' | 'switch'; account?: string }): void
}) {
  const [choice, setChoice] = useState<ResolveKind>('wait')
  const [account, setAccount] = useState('')

  useEffect(() => {
    setChoice('wait')
    setAccount(props.accounts?.find((candidate) => candidate.health === 'ready')?.slug ?? '')
  }, [props.open, props.wrapper, props.accounts])

  if (!props.open) return null

  const limited = props.limit?.active === true
  const scope = limited
    ? `Affects ${props.limit?.affectedSeats?.join(', ') || 'seats not recorded'} · parked ${props.limit?.parkedTasks?.join(', ') || 'tasks not recorded'}`
    : null
  const recommended = props.accounts?.find((candidate) => candidate.health === 'ready')

  const resolve = () => {
    if (choice === 'switch') props.onResolve({ kind: 'switch', account })
    else props.onResolve({ kind: choice })
  }

  return (
    <dialog
      open
      aria-labelledby="rate-limit-title"
      className="fixed inset-0 z-50 m-auto w-[min(42rem,calc(100%-2rem))] rounded-xl border border-border bg-surface p-0 text-fg shadow-xl backdrop:bg-bg/70"
    >
      <header className="flex items-start justify-between gap-4 border-b border-border px-5 py-4">
        <div>
          <h2 id="rate-limit-title" className="text-lg font-semibold">
            {limited ? `Rate-limited on ${props.wrapper}` : `${props.wrapper} capacity`}
          </h2>
          {limited && (
            <p className="mt-1 text-sm text-fg-muted">
              The provider paused new requests for account {props.limit?.account ?? 'not recorded'}.
              The run is alive; parked work resumes by itself.
            </p>
          )}
        </div>
        <button
          type="button"
          onClick={props.onClose}
          className="min-h-11 rounded-md px-3 text-sm font-semibold text-fg-muted hover:bg-surface-raised focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
        >
          Close
        </button>
      </header>

      {!limited ? (
        <p className="px-5 py-6 text-sm font-semibold text-success">
          No limit — account chain healthy
        </p>
      ) : (
        <div className="space-y-5 px-5 py-4">
          <section>
            <h3 className="text-xs font-semibold uppercase tracking-wider text-fg-subtle">
              What happened
            </h3>
            <p className="mt-2 text-sm text-fg-muted">{scope}</p>
          </section>

          <fieldset className="space-y-2">
            <legend className="text-xs font-semibold uppercase tracking-wider text-fg-subtle">
              Resolve
            </legend>
            <label className="flex min-h-11 items-center gap-3 rounded-md border border-border px-3 text-sm">
              <input
                type="radio"
                name="rate-limit-resolution"
                checked={choice === 'wait'}
                onChange={() => setChoice('wait')}
              />
              <span>
                <strong>Wait — safe</strong> · parked work resumes automatically
              </span>
            </label>
            <label className="flex min-h-11 items-center gap-3 rounded-md border border-border px-3 text-sm">
              <input
                type="radio"
                name="rate-limit-resolution"
                checked={choice === 'retry'}
                onChange={() => setChoice('retry')}
              />
              <span>
                <strong>Retry now</strong> · risks burning another wait attempt
              </span>
            </label>
            <label className="flex min-h-11 items-center gap-3 rounded-md border border-border px-3 text-sm">
              <input
                type="radio"
                name="rate-limit-resolution"
                checked={choice === 'switch'}
                disabled={!props.accounts?.some((candidate) => candidate.health === 'ready')}
                onChange={() => setChoice('switch')}
              />
              <span>
                <strong>Switch account</strong> · move future starts to a ready account
              </span>
            </label>
          </fieldset>

          {props.accounts ? (
            <div>
              <Select
                id="rate-limit-account"
                label={`${props.wrapper} account chain`}
                value={account}
                onValueChange={setAccount}
                options={props.accounts.map((candidate) => ({
                  value: candidate.slug,
                  label: `${candidate.slug} · ${candidate.health}${candidate.note ? ` · ${candidate.note}` : ''}`,
                  disabled: candidate.health !== 'ready',
                }))}
              />
              {recommended && (
                <p className="mt-2 text-sm text-fg-muted">
                  Recommendation: switch to {recommended.slug}; account reports ready.
                </p>
              )}
            </div>
          ) : (
            <p className="text-sm text-fg-muted">Account chain not recorded yet (B7)</p>
          )}

          <div className="flex justify-end border-t border-border pt-4">
            <LinkButton onClick={resolve} disabled={choice === 'switch' && !account}>
              Apply resolution
            </LinkButton>
          </div>
        </div>
      )}
    </dialog>
  )
}
