'use client'

import { useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { MODE_LABELS, ROLE_LABELS, contextGroupLabel, type AdminWorkspace, type UserContext } from '@/lib/domain/modes'

const BTN = 'rounded-lg bg-[#0f1b2d] px-3 py-1.5 text-xs font-bold text-white transition hover:bg-[#1c2d47] disabled:opacity-50'
const BTN_SOFT = 'rounded-lg border bg-white px-3 py-1.5 text-xs font-bold text-neutral-800 transition hover:bg-neutral-50 disabled:opacity-50'
const BTN_DANGER = 'rounded-lg border border-red-200 bg-red-50 px-3 py-1.5 text-xs font-bold text-red-700 transition hover:bg-red-100 disabled:opacity-50'
const fmt = (iso: string | null) => (iso ? new Date(iso).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : '—')

export function RolesWorkspaces({ active, pending, past, defaultKey, activeKey, isAdmin, adminDefault, workspaces }: {
  active: UserContext[]
  pending: UserContext[]
  past: UserContext[]
  defaultKey: string | null
  activeKey: string | null
  isAdmin: boolean
  adminDefault: string | null
  workspaces: AdminWorkspace[]
}) {
  const router = useRouter()
  const [busy, setBusy] = useState(false)
  const [removing, setRemoving] = useState<UserContext | null>(null)
  const [warning, setWarning] = useState<string | null>(null)

  async function call(body: Record<string, unknown>) {
    const r = await fetch('/api/modes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
    const json = await r.json().catch(() => ({}))
    if (!r.ok) throw new Error(json.error ?? 'Something went wrong.')
    return json as { next?: string; needs_choice?: boolean; cleared_default?: boolean }
  }
  async function open(c: UserContext) {
    setBusy(true)
    try { const j = await call({ op: 'switch', key: c.key }); router.push(j.next ?? '/dashboard'); router.refresh() }
    catch (e) { toast.error(e instanceof Error ? e.message : 'Could not open.'); setBusy(false) }
  }
  async function makeDefault(c: UserContext) {
    setBusy(true)
    try { await call({ op: 'set_default', key: c.key }); toast.success(`${MODE_LABELS[c.roleType]} is now your default.`); router.refresh() }
    catch (e) { toast.error(e instanceof Error ? e.message : 'Could not set the default.') } finally { setBusy(false) }
  }
  async function askRemove(c: UserContext) {
    // The server owns the rule; ask it first so the only Company Admin is stopped here too.
    setBusy(true)
    try {
      const r = await fetch('/api/modes/removal-check', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: c.key }) })
      const json = await r.json().catch(() => ({}))
      if (!r.ok) { toast.error(json.error ?? 'This role cannot be removed.'); return }
      setWarning(json.warning as string)
      setRemoving(c)
    } finally { setBusy(false) }
  }
  async function confirmRemove() {
    if (!removing) return
    setBusy(true)
    try {
      const j = await call({ op: 'remove_role', key: removing.key })
      toast.success(`${ROLE_LABELS[removing.roleType]} removed. Your other roles are untouched.`)
      setRemoving(null)
      if (j.needs_choice) router.push('/modes')
      else if (j.next) router.push(j.next)
      router.refresh()
    } catch (e) { toast.error(e instanceof Error ? e.message : 'Could not remove the role.') } finally { setBusy(false) }
  }

  return (
    <div className="mt-6 space-y-6">
      {isAdmin && (
        <section className="rounded-2xl border bg-white p-4">
          <h2 className="text-sm font-bold">Admin workspaces</h2>
          <p className="mt-1 text-xs text-neutral-500">Your access comes from your platform role. Opening a product view is a preview for support and testing — it never creates a company role for you.</p>
          <div className="mt-3 grid gap-2 sm:grid-cols-2">
            {workspaces.map((w) => (
              <div key={w.key} className="flex items-center justify-between gap-2 rounded-xl border p-2.5">
                <span className="text-xs"><span className="font-semibold">{w.label}</span>{adminDefault === w.key && <span className="ml-1.5 text-[10px] text-neutral-500">default</span>}{w.group === 'product' && <span className="block text-[10px] text-neutral-400">Admin preview</span>}</span>
                <Link href={w.href} className={BTN_SOFT}>Open</Link>
              </div>
            ))}
          </div>
        </section>
      )}

      <section>
        <h2 className="text-sm font-bold">Active roles</h2>
        {active.length === 0 ? (
          <p className="mt-2 rounded-xl border border-dashed p-4 text-sm text-neutral-500">No active roles yet. A company can invite you, or you can request access from a company page.</p>
        ) : (
          <ul className="mt-2 space-y-2">
            {active.map((c) => (
              <li key={c.key} className="rounded-2xl border bg-white p-4">
                <div className="flex flex-wrap items-start justify-between gap-3">
                  <div>
                    <p className="text-sm font-bold">{c.companyName ?? 'Independent'}</p>
                    <p className="text-sm text-neutral-700">{ROLE_LABELS[c.roleType]}</p>
                    <p 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>
                      {c.permission === 'company_admin' && <span className="rounded-full bg-blue-50 px-2 py-0.5 font-semibold text-blue-800">Company Admin</span>}
                      {defaultKey === c.key && <span className="rounded-full bg-neutral-100 px-2 py-0.5 font-semibold text-neutral-600">Default mode</span>}
                      {activeKey === c.key && <span className="rounded-full bg-[#0f1b2d] px-2 py-0.5 font-semibold text-white">In use now</span>}
                      <span className="text-neutral-500">{contextGroupLabel(c)} · added {fmt(c.addedAt)}</span>
                    </p>
                  </div>
                  <div className="flex flex-wrap gap-1.5">
                    <button disabled={busy} onClick={() => open(c)} className={BTN}>Open</button>
                    {defaultKey !== c.key && <button disabled={busy} onClick={() => makeDefault(c)} className={BTN_SOFT}>Set default</button>}
                    {!c.independent && <button disabled={busy} onClick={() => askRemove(c)} className={BTN_DANGER}>Remove role</button>}
                  </div>
                </div>
              </li>
            ))}
          </ul>
        )}
      </section>

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

      {past.length > 0 && (
        <section>
          <h2 className="text-sm font-bold">Past roles</h2>
          <p className="text-xs text-neutral-500">Kept for the record. Your work under these roles is still attributed to you.</p>
          <ul className="mt-2 space-y-1.5 text-xs text-neutral-600">
            {past.map((c) => (
              <li key={c.key} className="rounded-xl border bg-neutral-50 p-2.5">
                <span className="font-semibold">{ROLE_LABELS[c.roleType]} — {c.companyName ?? 'Independent'}</span>
                <span className="ml-2">{c.status === 'revoked' ? 'Revoked' : 'Removed'} {fmt(c.removedAt)}{c.removedBy ? ` by ${c.removedBy}` : ''}</span>
              </li>
            ))}
          </ul>
        </section>
      )}

      <Dialog open={!!removing} onOpenChange={(o) => !o && setRemoving(null)}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Remove {removing ? ROLE_LABELS[removing.roleType] : ''} role?</DialogTitle>
            <DialogDescription>{warning}</DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <button onClick={() => setRemoving(null)} className={BTN_SOFT}>Cancel</button>
            <button disabled={busy} onClick={confirmRemove} className={BTN_DANGER}>{busy ? 'Removing…' : 'Remove role'}</button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
