'use client'

import { useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'
import { MODE_LABELS, ROLE_LABELS, contextGroupLabel, type AdminWorkspace, type UserContext } from '@/lib/domain/modes'

/**
 * The workspace chooser. Regular users pick a role at a company; the admin
 * picks a workspace, with product views clearly marked as previews.
 */
export function ModeSelector({ name, isAdmin, contexts, pending, workspaces, defaultKey, adminDefault }: {
  name: string
  isAdmin: boolean
  contexts: UserContext[]
  pending: UserContext[]
  workspaces: AdminWorkspace[]
  defaultKey: string | null
  adminDefault: string | null
}) {
  const router = useRouter()
  const [setDefault, setSetDefault] = useState(false)
  const [busy, setBusy] = useState<string | null>(null)

  async function open(body: Record<string, unknown>, key: string) {
    setBusy(key)
    try {
      const r = await fetch('/api/modes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...body, set_default: setDefault }) })
      const json = await r.json().catch(() => ({}))
      if (!r.ok) throw new Error(json.error ?? 'Could not open that workspace.')
      router.push(json.next as string)
      router.refresh()
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Could not open that workspace.')
      setBusy(null)
    }
  }

  const card = 'w-full rounded-2xl border bg-white p-4 text-left transition hover:border-[#0f1b2d] hover:shadow-sm disabled:opacity-50'
  return (
    <main className="min-h-screen bg-neutral-50">
      <div className="mx-auto max-w-2xl px-4 py-10">
        <div className="mb-6 flex items-center gap-2">
          <span className="grid h-9 w-9 place-items-center rounded-lg bg-[#0f1b2d] text-sm font-extrabold text-[#f5a623]">H</span>
          <span className="text-sm font-bold">HeavyHaul Agent</span>
        </div>

        {isAdmin ? (
          <>
            <h1 className="text-2xl font-bold">Choose your workspace</h1>
            <p className="mt-1 text-sm text-neutral-500">Opening a product view is a preview for support and testing. It never creates a company role for you.</p>
            {(['admin', 'product'] as const).map((group) => (
              <section key={group} className="mt-5">
                <p className="text-xs font-bold uppercase tracking-wide text-neutral-400">{group === 'admin' ? 'Admin' : 'Product views'}</p>
                <div className="mt-2 grid gap-2 sm:grid-cols-2">
                  {workspaces.filter((w) => w.group === group).map((w) => (
                    <button key={w.key} disabled={busy !== null} onClick={() => open({ op: 'admin_preview', workspace: w.key }, w.key)} className={card}>
                      <span className="text-sm font-bold">{w.label}</span>
                      {adminDefault === w.key && <span className="ml-2 rounded-full bg-neutral-100 px-2 py-0.5 text-[10px] font-semibold text-neutral-600">your default</span>}
                      {w.group === 'product' && <span className="mt-0.5 block text-[11px] text-neutral-500">Admin preview</span>}
                    </button>
                  ))}
                </div>
              </section>
            ))}
          </>
        ) : (
          <>
            <h1 className="text-2xl font-bold">Welcome back, {name.split(' ')[0]}</h1>
            <p className="mt-1 text-sm text-neutral-500">You have access to more than one workspace. Choose how you want to continue.</p>
            <div className="mt-5 grid gap-2">
              {contexts.map((c) => (
                <button key={c.key} disabled={busy !== null} onClick={() => open({ op: 'switch', key: c.key }, c.key)} className={card}>
                  <span className="text-sm font-bold">{c.companyName ?? 'Independent'}</span>
                  <span className="mt-0.5 block text-sm text-neutral-700">{ROLE_LABELS[c.roleType]}</span>
                  <span className="mt-1 flex flex-wrap items-center gap-2 text-[11px]">
                    <span className="rounded-full bg-green-50 px-2 py-0.5 font-semibold text-green-800">Verified</span>
                    <span className="text-neutral-500">Opens the {contextGroupLabel(c)} workspace</span>
                    {defaultKey === c.key && <span className="rounded-full bg-neutral-100 px-2 py-0.5 font-semibold text-neutral-600">your default</span>}
                  </span>
                </button>
              ))}
            </div>
          </>
        )}

        <label className="mt-4 flex items-center gap-2 text-sm">
          <input type="checkbox" checked={setDefault} onChange={(e) => setSetDefault(e.target.checked)} />
          Set the selected {isAdmin ? 'view' : 'mode'} as my default
        </label>

        {pending.length > 0 && (
          <section className="mt-6 rounded-2xl border border-amber-200 bg-amber-50 p-4">
            <p className="text-sm font-bold text-amber-900">Waiting for verification</p>
            <ul className="mt-1 space-y-1 text-xs text-amber-900">
              {pending.map((c) => (
                <li key={c.key} className="flex flex-wrap items-center gap-2">
                  <span className="font-semibold">{ROLE_LABELS[c.roleType]} — {c.companyName ?? 'Independent'}</span>
                  <span>Waiting for verification</span>
                  <Link href="/settings/roles" className="font-semibold underline">View verification status</Link>
                </li>
              ))}
            </ul>
            <p className="mt-1 text-[11px] text-amber-800">{MODE_LABELS[pending[0].roleType]} opens once the company verifies you.</p>
          </section>
        )}

        <p className="mt-6 text-xs text-neutral-500">
          You can change this any time from <Link href="/settings/roles" className="font-semibold underline">Roles &amp; Workspaces</Link> or the Switch Mode menu.
        </p>
      </div>
    </main>
  )
}
