'use client'

import { stateName } from '@/lib/domain/states'
import type { PilotInviteAccess } from '@/lib/domain/pilot'

/**
 * "Pilot access on this trip" — shown in the trip workspace invite form when
 * the role being invited is `pilot` (Nash, 2026-09-12): "he needs to choose
 * for that trip he wants to give all states or select certain states or
 * certain permits… if he doesn't choose anything, he can choose all decide
 * later and send that invitation."
 *
 * Phase 1: the choice travels with the invitation and is written to the trip
 * history. Enforcement on the pilot's side (what they can open) arrives with
 * the pilot backend phase — the pilot workspace preview shows the intended
 * result on demo data.
 */
export function PilotAccessChooser({
  permits,
  value,
  onChange,
}: {
  permits: { id: string; state_code: string; permit_number: string | null }[]
  value: PilotInviteAccess
  onChange: (next: PilotInviteAccess) => void
}) {
  const states = [...new Set(permits.map((p) => p.state_code).filter(Boolean))]
  const options: { type: PilotInviteAccess['type']; label: string; hint: string }[] = [
    { type: 'full_trip', label: 'All states (full trip)', hint: 'Every permit and every state on this trip. The rate confirmation is never included.' },
    { type: 'states', label: 'Select states', hint: 'Every permit for the chosen states — including permits uploaded later.' },
    { type: 'permits', label: 'Select permits', hint: 'Only the chosen permits. Later permits are not shared unless you add them.' },
    { type: 'decide_later', label: 'Decide later', hint: 'Send the invitation now; the pilot sees no permits until you share some.' },
  ]

  function pick(type: PilotInviteAccess['type']) {
    if (type === 'full_trip' || type === 'decide_later') onChange({ type })
    else if (type === 'states') onChange({ type, states: [] })
    else onChange({ type, permit_ids: [], labels: [] })
  }

  return (
    <div className="space-y-2 rounded-xl border border-amber-200 bg-amber-50/60 p-3 sm:col-span-2">
      <p className="text-xs font-bold uppercase tracking-wide text-neutral-600">Pilot access on this trip</p>
      <div className="grid gap-1.5 sm:grid-cols-2">
        {options.map((o) => (
          <label
            key={o.type}
            className={`flex cursor-pointer items-start gap-2 rounded-lg border p-2 text-xs transition ${
              value.type === o.type ? 'border-[#0f1b2d] bg-white' : 'border-transparent bg-white/60 hover:border-neutral-300'
            }`}
          >
            <input type="radio" name="pilot_access_type" className="mt-0.5" checked={value.type === o.type} onChange={() => pick(o.type)} />
            <span>
              <span className="block font-semibold">{o.label}</span>
              <span className="text-neutral-500">{o.hint}</span>
            </span>
          </label>
        ))}
      </div>

      {value.type === 'states' && (
        <div className="flex flex-wrap gap-1.5 pt-1">
          {states.length === 0 && <p className="text-xs text-neutral-500">No permits on this trip yet, so there are no states to pick. Choose “Decide later” or “All states”.</p>}
          {states.map((s) => {
            const on = value.states.includes(s)
            return (
              <button
                key={s}
                type="button"
                onClick={() => onChange({ type: 'states', states: on ? value.states.filter((x) => x !== s) : [...value.states, s] })}
                className={`rounded-full px-2.5 py-1 text-xs font-semibold ring-1 ring-inset ${on ? 'bg-[#0f1b2d] text-white ring-[#0f1b2d]' : 'bg-white text-neutral-600 ring-neutral-300'}`}
              >
                {s} · {stateName(s) || s}
              </button>
            )
          })}
        </div>
      )}

      {value.type === 'permits' && (
        <div className="space-y-1 pt-1">
          {permits.length === 0 && <p className="text-xs text-neutral-500">No permits on this trip yet. Choose “Decide later” or “All states”.</p>}
          {permits.map((p) => {
            const label = `${p.state_code} · ${p.permit_number || 'permit'}`
            const on = value.permit_ids.includes(p.id)
            return (
              <label key={p.id} className="flex items-center gap-2 text-xs">
                <input
                  type="checkbox"
                  checked={on}
                  onChange={() =>
                    onChange({
                      type: 'permits',
                      permit_ids: on ? value.permit_ids.filter((x) => x !== p.id) : [...value.permit_ids, p.id],
                      labels: on ? (value.labels ?? []).filter((x) => x !== label) : [...(value.labels ?? []), label],
                    })
                  }
                />
                <span className="font-mono">{label}</span>
              </label>
            )
          })}
        </div>
      )}
    </div>
  )
}
