'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'
import type { CarrierContact, ContactRole } from '@/types/db'

/**
 * The dispatcher's saved people — the Drivers tab (Task 98, 2026-09-09).
 *
 * Nash: "Maybe this page under My Fleet, as the carrier dispatch, maybe this
 * page is better for me to invite drivers? To save, like, my contacts, kind
 * of? My contacts — instead of Fleet, should we have their drivers? And I can
 * just add my email, phone number, and name of the driver, and it kind of
 * triggers an invite email to him to create an account and to join."
 *
 * He reached this after rejecting his own first idea for the tab — truck and
 * trailer history — in the same breath: "maybe this is not a good idea since
 * it doesn't matter about the units… The dispatcher is not using this." So
 * this tab holds people, not units.
 *
 * Saving here is what makes Task 99's picker useful: the four fields get typed
 * once instead of on every trip.
 */

const BLANK = { name: '', email: '', phone: '', phone_ext: '', role: 'driver' as ContactRole }

export function ContactsPanel({
  available,
  contacts,
}: {
  /** False when migration 0014 is not applied — the list stays honest. */
  available: boolean
  contacts: CarrierContact[]
}) {
  const router = useRouter()
  const [form, setForm] = useState(BLANK)
  const [editing, setEditing] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)
  const [query, setQuery] = useState('')
  const [open, setOpen] = useState(false)

  const set = (k: keyof typeof form, v: string) => setForm((f) => ({ ...f, [k]: v }))

  async function call(body: Record<string, unknown>) {
    setBusy(true)
    try {
      const res = await fetch('/api/contacts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      })
      const json = await res.json().catch(() => ({}))
      if (!res.ok) {
        toast.error(json.error ?? 'Could not save')
        return null
      }
      router.refresh()
      return json
    } finally {
      setBusy(false)
    }
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault()
    if (editing) {
      const json = await call({ op: 'update', id: editing, ...form })
      if (json) {
        toast.success('Contact updated')
        setEditing(null)
        setForm(BLANK)
        setOpen(false)
      }
      return
    }
    const json = await call({ op: 'add', invite: true, ...form })
    if (json) {
      toast.success(
        json.already_a_user
          ? `${form.name} is saved — they already have an account`
          : `${form.name} is saved. The invitation to create an account sends when the email service is connected.`,
      )
      setForm(BLANK)
      setOpen(false)
    }
  }

  async function remove(c: CarrierContact) {
    if (!confirm(`Remove ${c.name} from your contacts?`)) return
    const json = await call({ op: 'remove', id: c.id })
    if (json) toast.success('Contact removed')
  }

  function startEdit(c: CarrierContact) {
    setEditing(c.id)
    setForm({
      name: c.name,
      email: c.email,
      phone: c.phone ?? '',
      phone_ext: c.phone_ext ?? '',
      role: c.role,
    })
    setOpen(true)
  }

  const term = query.trim().toLowerCase()
  const shown = term
    ? contacts.filter(
        (c) => c.name.toLowerCase().includes(term) || c.email.toLowerCase().includes(term),
      )
    : contacts
  const drivers = shown.filter((c) => c.role === 'driver')
  const brokers = shown.filter((c) => c.role === 'broker')

  if (!available) {
    return (
      <div className="mt-6 rounded-2xl border border-dashed border-line bg-white p-14 text-center">
        <p className="text-[10px] font-bold uppercase tracking-[0.14em] text-slate-body/70">Drivers</p>
        <p className="mt-2 text-sm text-slate-body">
          Saved contacts need database migration 0014 —{' '}
          <span className="font-mono text-xs">supabase/migrations/0014_carrier_contacts.sql</span> in
          the Supabase SQL editor.
        </p>
      </div>
    )
  }

  return (
    <div className="mt-6 space-y-5">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h2 className="text-sm font-bold tracking-tight">Your drivers and brokers</h2>
          <p className="mt-0.5 text-xs text-slate-body">
            Save the people you work with once — then pick them when you create a trip instead of
            typing their details again.
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search name or email"
            className="rounded-lg border border-line px-3 py-2 text-sm"
          />
          <button
            onClick={() => {
              setEditing(null)
              setForm(BLANK)
              setOpen((o) => !o)
            }}
            className="rounded-lg bg-navy-900 px-4 py-2 text-sm font-bold text-white transition hover:bg-navy-800"
          >
            + Add contact
          </button>
        </div>
      </div>

      {open && (
        <form
          onSubmit={submit}
          className="grid gap-3 rounded-2xl border border-line bg-white p-4 sm:grid-cols-2"
        >
          <label className="space-y-1">
            <span className="text-[11px] font-bold uppercase text-slate-body/70">Role</span>
            <select
              value={form.role}
              onChange={(e) => set('role', e.target.value)}
              className="w-full rounded-lg border border-line px-3 py-2 text-sm"
            >
              <option value="driver">Driver</option>
              <option value="broker">Broker</option>
            </select>
          </label>
          <label className="space-y-1">
            <span className="text-[11px] font-bold uppercase text-slate-body/70">
              Full name <span className="text-danger">*</span>
            </span>
            <input
              required
              value={form.name}
              onChange={(e) => set('name', e.target.value)}
              className="w-full rounded-lg border border-line px-3 py-2 text-sm"
            />
          </label>
          <label className="space-y-1">
            <span className="text-[11px] font-bold uppercase text-slate-body/70">
              Email <span className="text-danger">*</span>
            </span>
            <input
              required
              type="email"
              value={form.email}
              onChange={(e) => set('email', e.target.value)}
              className="w-full rounded-lg border border-line px-3 py-2 text-sm"
            />
          </label>
          <div className="flex gap-2">
            <label className="flex-1 space-y-1">
              <span className="text-[11px] font-bold uppercase text-slate-body/70">
                Phone <span className="text-danger">*</span>
              </span>
              <input
                required
                value={form.phone}
                onChange={(e) => set('phone', e.target.value)}
                className="w-full rounded-lg border border-line px-3 py-2 text-sm"
              />
            </label>
            <label className="w-24 space-y-1">
              <span className="text-[11px] font-bold uppercase text-slate-body/70">Ext.</span>
              <input
                value={form.phone_ext}
                onChange={(e) => set('phone_ext', e.target.value)}
                className="w-full rounded-lg border border-line px-3 py-2 text-sm"
              />
            </label>
          </div>
          <div className="flex items-center gap-2 sm:col-span-2">
            <button
              type="submit"
              disabled={busy}
              className="rounded-lg bg-navy-900 px-4 py-2 text-sm font-bold text-white disabled:opacity-60"
            >
              {busy ? 'Saving…' : editing ? 'Save changes' : 'Save contact'}
            </button>
            <button
              type="button"
              onClick={() => {
                setOpen(false)
                setEditing(null)
                setForm(BLANK)
              }}
              className="rounded-lg px-3 py-2 text-sm font-semibold text-slate-body"
            >
              Cancel
            </button>
            {!editing && (
              <p className="text-[11px] text-slate-body/70">
                Saving invites them to create an account. Emails activate with the backend.
              </p>
            )}
          </div>
        </form>
      )}

      <ContactGroup title="Drivers" contacts={drivers} onEdit={startEdit} onRemove={remove} busy={busy} />
      <ContactGroup title="Brokers" contacts={brokers} onEdit={startEdit} onRemove={remove} busy={busy} />

      <p className="text-[11px] leading-relaxed text-slate-body/60">
        VIN-based fleet monitoring — subscription per truck, driver app status and curfew
        monitoring — arrives in a later phase.
      </p>
    </div>
  )
}

function ContactGroup({
  title,
  contacts,
  onEdit,
  onRemove,
  busy,
}: {
  title: string
  contacts: CarrierContact[]
  onEdit: (c: CarrierContact) => void
  onRemove: (c: CarrierContact) => void
  busy: boolean
}) {
  return (
    <section>
      <h3 className="mb-2 text-[10px] font-bold uppercase tracking-[0.14em] text-slate-body/70">
        {title} ({contacts.length})
      </h3>
      {contacts.length === 0 ? (
        <p className="rounded-xl border border-dashed border-line p-4 text-center text-xs text-slate-body">
          No {title.toLowerCase()} saved yet.
        </p>
      ) : (
        <div className="space-y-2">
          {contacts.map((c) => (
            <div
              key={c.id}
              className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-line bg-white p-3 text-sm"
            >
              <div className="min-w-0">
                <p className="font-bold">
                  {c.name}
                  {c.user_id ? (
                    <span className="ml-2 rounded-full bg-ok-bg px-2 py-0.5 text-[10px] font-semibold text-ok">
                      Has an account
                    </span>
                  ) : c.invited_at ? (
                    <span className="ml-2 rounded-full bg-paper px-2 py-0.5 text-[10px] font-semibold text-slate-body ring-1 ring-line">
                      Invitation pending
                    </span>
                  ) : null}
                </p>
                <p className="truncate text-xs text-slate-body">
                  {c.email}
                  {c.phone ? ` · ${c.phone}` : ''}
                  {c.phone_ext ? ` ext. ${c.phone_ext}` : ''}
                </p>
              </div>
              <div className="flex shrink-0 gap-2">
                <button
                  onClick={() => onEdit(c)}
                  disabled={busy}
                  className="rounded-lg border border-line px-3 py-1.5 text-xs font-semibold transition hover:border-navy-500"
                >
                  Edit
                </button>
                <button
                  onClick={() => onRemove(c)}
                  disabled={busy}
                  className="rounded-lg px-3 py-1.5 text-xs font-semibold text-danger transition hover:bg-danger-bg"
                >
                  Remove
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </section>
  )
}
