'use client'

import { useState } from 'react'
import type { CarrierContact, ContactRole } from '@/types/db'

/**
 * Pick a saved driver or broker instead of retyping them (Task 99, 2026-09-09).
 *
 * Nash: "when I go to create a trip, I have to invite drivers, and I have to
 * do it every time — put the name and the email and the phone number and the
 * extension. Can I have an ability to choose any of my existing drivers?
 * Maybe there is brokers that I worked with before, and drivers that I worked
 * with before should be displayed in there."
 *
 * The one firm rule he gave: "We do have to keep them distinguished —
 * separate drivers and brokers — when I go to choose." So the two groups are
 * never mixed into one list; picking a broker where a driver belongs would put
 * the wrong person in a role on a live load.
 *
 * Picking fills the existing draft fields and leaves them editable — the
 * caller's own validated "Add" path still does the adding, so there is no
 * second code path that can drift from it.
 */

export interface PickedContact {
  role: ContactRole
  name: string
  email: string
  phone: string
  phone_ext: string
}

export function ContactPicker({
  drivers = [],
  brokers = [],
  dispatchers,
  onPick,
  alreadyAdded = [],
  className = '',
}: {
  drivers?: CarrierContact[]
  brokers?: CarrierContact[]
  /** A freight broker's saved carrier dispatchers (2026-09-13). When given, this is the only group shown. */
  dispatchers?: CarrierContact[]
  onPick: (c: PickedContact) => void
  /** Emails already on this trip — shown as added rather than offered twice. */
  alreadyAdded?: string[]
  className?: string
}) {
  const [group, setGroup] = useState<ContactRole>(dispatchers ? 'dispatcher' : 'driver')
  // Nothing saved yet: render nothing at all, so a dispatcher with no contacts
  // sees exactly the form they see today.
  if (dispatchers ? dispatchers.length === 0 : drivers.length === 0 && brokers.length === 0) return null

  const taken = new Set(alreadyAdded.map((e) => e.trim().toLowerCase()))
  const list = dispatchers ? dispatchers : group === 'driver' ? drivers : brokers

  return (
    <div className={`rounded-xl border border-line bg-paper p-3 ${className}`}>
      <div className="flex flex-wrap items-center justify-between gap-2">
        <p className="text-[11px] font-bold uppercase tracking-wide text-slate-body/70">
          Choose from your contacts
        </p>
        {/* Drivers and brokers stay separate — Nash's explicit rule. */}
        {dispatchers ? (
          <span className="rounded-md bg-white px-2.5 py-1 text-[11px] font-bold text-slate-body ring-1 ring-line">Dispatchers ({dispatchers.length})</span>
        ) : (
        <div className="flex gap-1 rounded-lg bg-white p-0.5 ring-1 ring-line">
          {(
            [
              ['driver', `Drivers (${drivers.length})`],
              ['broker', `Brokers (${brokers.length})`],
            ] as const
          ).map(([key, label]) => (
            <button
              key={key}
              type="button"
              onClick={() => setGroup(key)}
              className={`rounded-md px-2.5 py-1 text-[11px] font-bold transition ${
                group === key ? 'bg-navy-900 text-white' : 'text-slate-body hover:text-ink'
              }`}
            >
              {label}
            </button>
          ))}
        </div>
        )}
      </div>

      {list.length === 0 ? (
        <p className="mt-2 text-xs text-slate-body">
          No saved {group === 'driver' ? 'drivers' : group === 'broker' ? 'brokers' : 'dispatchers'} yet.
        </p>
      ) : (
        <div className="mt-2 flex flex-wrap gap-1.5">
          {list.map((c) => {
            const added = taken.has(c.email.toLowerCase())
            return (
              <button
                key={c.id}
                type="button"
                disabled={added}
                onClick={() =>
                  onPick({
                    role: c.role,
                    name: c.name,
                    email: c.email,
                    phone: c.phone ?? '',
                    phone_ext: c.phone_ext ?? '',
                  })
                }
                title={added ? `${c.name} is already on this trip` : `${c.name} · ${c.email}`}
                className={`rounded-full border px-3 py-1.5 text-xs font-semibold transition ${
                  added
                    ? 'cursor-not-allowed border-line bg-white text-slate-body/40'
                    : 'border-line bg-white hover:border-navy-500'
                }`}
              >
                {c.name}
                {added ? ' ✓' : ''}
              </button>
            )
          })}
        </div>
      )}
      <p className="mt-2 text-[10px] text-slate-body/60">
        Picking someone fills the fields below — you can still edit them before adding.
      </p>
    </div>
  )
}
