'use client'

import { useState } from 'react'
import { toast } from 'sonner'
import { CURRENT_PLAN } from '@/lib/demo/credits'
import { canUseBusinessTools, driverCanSeeInvoices, money, type PlanName } from '@/lib/domain/invoicing'
import type { PilotAccountType } from '@/lib/domain/pilot'
import {
  useDriverPlanPreview,
  useExpenses,
  useInvoiceLog,
  useInvoices,
  useOwnerPlanPreview,
  type PilotInvoice,
} from '@/lib/demo/invoicing-store'
import { buildInvoicePdf, openPdf } from '@/lib/demo/invoice-pdf'
import { DEMO_PILOT_COMPANY, demoDriver, type DemoPilotAssignment } from '@/lib/demo/pilot'
import { ExpenseTracker } from './expense-tracker'
import { InvoiceBuilder, type InvoiceContext } from './invoice-builder'
import { LockedProFeature } from './locked-pro'

/**
 * "My Pilot" business tools for one assignment: invoice history, Create
 * Invoice, Expenses — plan-gated on the assignment OWNER's plan (article §20,
 * §22). Used by the pilot dispatch trip workspace tab and the pilot driver's
 * My Pilot Car pane.
 *
 * Owner rule: managed by a pilot company → the company; accepted directly by
 * an independent driver → the driver. A driver under a Pro company sees the
 * company's invoices/expenses read-only (default pending Nash's confirmation).
 */
export function PilotToolsPanel({
  assignment: a,
  actor,
  /** Independent driver = no approved pilot company on the assignment. */
  independentDriver = false,
  compact = false,
}: {
  assignment: DemoPilotAssignment
  actor: PilotAccountType
  independentDriver?: boolean
  compact?: boolean
}) {
  const ownerType: PilotAccountType = independentDriver ? 'pilot_driver' : 'pilot_company'
  const drv = demoDriver(a.pilotDriverId)
  const ownerName = ownerType === 'pilot_company' ? DEMO_PILOT_COMPANY.name : drv?.name ?? 'Pilot driver'
  const ownerContact =
    ownerType === 'pilot_company'
      ? `${DEMO_PILOT_COMPANY.mainContact} · ${DEMO_PILOT_COMPANY.phone} · ${DEMO_PILOT_COMPANY.email}`
      : `${drv?.phone ?? ''} · ${drv?.email ?? ''}`
  const actorName = actor === 'pilot_company' ? DEMO_PILOT_COMPANY.mainContact.split(' (')[0] : drv?.name ?? 'Pilot driver'
  /** The actor may manage tools only when they ARE the owner. */
  const isOwner = actor === ownerType

  // Everyone is on Free until payments connect; the preview switch shows the
  // Pro/Pro Plus states for design review (admin-only screens).
  const { plan, setPlan } = useOwnerPlanPreview(CURRENT_PLAN.name as PlanName)
  const { plan: driverPlan, setPlan: setDriverPlan } = useDriverPlanPreview(CURRENT_PLAN.name as PlanName)
  // Owner's plan decides who may create; a driver who is NOT the owner needs
  // his own Pro/Pro Plus plan just to SEE invoices (Nash, 2026-09-12).
  const driverViewing = actor === 'pilot_driver' && !isOwner
  const effectivePlan = driverViewing ? driverPlan : plan
  const unlocked = driverViewing ? driverCanSeeInvoices(driverPlan) : canUseBusinessTools(plan)

  const { invoices, save } = useInvoices()
  const { expenses } = useExpenses()
  const { log, append } = useInvoiceLog()
  const mine = invoices.filter((i) => i.assignmentId === a.id)
  const [editing, setEditing] = useState<PilotInvoice | 'new' | null>(null)

  const ctx: InvoiceContext = {
    assignment: a,
    ownerType,
    ownerName,
    ownerContact,
    actorName,
    brokerInvitedPilot: a.invitedBy === 'broker',
    pilotInvitedBroker: false,
    brokerEmail: 'erin@summitfreight.com',
  }

  async function viewPdf(inv: PilotInvoice) {
    openPdf(await buildInvoicePdf(inv, expenses), `${inv.invoiceNumber}.pdf`, 'view')
    append({ action: 'Invoice viewed', detail: `${inv.invoiceNumber} · ${a.ref} · by ${actorName}` })
  }

  if (editing) {
    return <InvoiceBuilder ctx={ctx} existing={editing === 'new' ? undefined : editing} onClose={() => setEditing(null)} />
  }

  return (
    <div className={compact ? 'space-y-3' : 'space-y-4'}>
      {/* Admin preview switch — the owner's plan */}
      <div className="rounded-xl border border-amber-300 bg-amber-50 px-3 py-2 text-[11px] text-amber-900">
        <span className="font-semibold">Design preview — {driverViewing ? 'your plan (driver)' : "owner's plan"}:</span>{' '}
        {(['Free', 'Starter', 'Pro', 'Pro Plus'] as PlanName[]).map((p) => (
          <button key={p} onClick={() => (driverViewing ? setDriverPlan(p) : setPlan(p))} className={`ml-1 rounded-full px-2 py-0.5 font-semibold ${effectivePlan === p ? 'bg-amber-900 text-white' : 'bg-white/70 hover:bg-white'}`}>{p}</button>
        ))}
        <span className="mt-1 block text-amber-800/80">
          Invoice owner: <span className="font-semibold">{ownerName}</span> ({ownerType === 'pilot_company' ? 'pilot company manages this assignment' : 'independent pilot driver'}). Same membership plans as every account.{' '}
          {driverViewing ? 'A driver sees invoices only on his own Pro or Pro Plus plan.' : 'Pro or Pro Plus unlocks these tools.'}
        </span>
      </div>

      {!unlocked ? (
        <LockedProFeature plan={effectivePlan} feature="invoice" />
      ) : (
        <>
          <div className="flex items-center justify-between">
            <p className="text-[10px] font-bold uppercase tracking-[0.14em] text-slate-body/70">Invoices · {mine.length}</p>
            {isOwner ? (
              <button onClick={() => setEditing('new')} className="rounded-lg bg-amber-brand px-3 py-1.5 text-xs font-bold text-navy-950 hover:bg-amber-deep">Create Invoice</button>
            ) : (
              <span className="text-[11px] text-slate-body">{ownerName} creates invoices for this assignment</span>
            )}
          </div>
          {mine.length === 0 ? (
            <p className="rounded-2xl border border-dashed border-line bg-white p-6 text-center text-xs text-slate-body">No invoices for this assignment yet.</p>
          ) : (
            <div className="divide-y divide-line rounded-2xl border border-line bg-white">
              {mine.map((inv) => (
                <div key={inv.id} className="flex flex-wrap items-center justify-between gap-2 px-4 py-2.5 text-xs">
                  <div>
                    <p className="font-semibold">{inv.invoiceNumber} <StatusPill status={inv.status} /></p>
                    <p className="text-slate-body">{inv.invoiceDate} · due {inv.dueDate ?? (inv.dueDateKey === 'asap' ? 'ASAP' : 'not set')} · {inv.calc.selectedBaseType} base · to {inv.billToContactEmail}</p>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="font-bold">{money(inv.calc.invoiceTotal)}</span>
                    <button onClick={() => viewPdf(inv)} className="rounded-lg border border-line px-2 py-1 text-[11px] font-semibold">View PDF</button>
                    {isOwner && inv.status !== 'Cancelled' && (
                      <button onClick={() => setEditing(inv)} className="rounded-lg border border-line px-2 py-1 text-[11px] font-semibold">{inv.status === 'Draft' ? 'Edit / Send' : 'Open'}</button>
                    )}
                    {isOwner && inv.status === 'Sent' && (
                      <button onClick={() => { save({ ...inv, status: 'Paid', paidAt: new Date().toISOString() }); toast.success(`${inv.invoiceNumber} marked Paid`) }} className="rounded-lg border border-line px-2 py-1 text-[11px] font-semibold text-ok">Mark Paid</button>
                    )}
                    {isOwner && (inv.status === 'Draft' || inv.status === 'Sent') && (
                      <button onClick={() => { save({ ...inv, status: 'Cancelled' }); toast.success(`${inv.invoiceNumber} cancelled`) }} className="text-[11px] font-semibold text-slate-body hover:text-danger">Cancel</button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}

          <ExpenseTracker
            assignmentId={a.id}
            tripRef={a.ref}
            ownerType={ownerType}
            ownerName={ownerName}
            actorName={actorName}
            readOnly={!isOwner}
          />

          {log.filter((e) => e.detail.includes(a.ref)).length > 0 && (
            <div className="rounded-2xl border border-line bg-white p-4 text-xs">
              <p className="text-[10px] font-bold uppercase tracking-[0.14em] text-slate-body/70">Invoice log</p>
              <div className="mt-1.5 space-y-1">
                {log.filter((e) => e.detail.includes(a.ref)).slice(0, 8).map((e, i) => (
                  <p key={i}><span className="font-mono text-slate-body">{e.at.slice(0, 16).replace('T', ' ')}</span> · <span className="font-semibold">{e.action}</span> — {e.detail}</p>
                ))}
              </div>
            </div>
          )}
        </>
      )}
    </div>
  )
}

export function StatusPill({ status }: { status: PilotInvoice['status'] }) {
  const style =
    status === 'Paid' ? 'bg-ok-bg text-ok ring-green-200' : status === 'Sent' ? 'bg-info-bg text-info ring-blue-200' : status === 'Cancelled' ? 'bg-neutral-100 text-slate-body ring-neutral-200' : 'bg-warn-bg text-warn ring-amber-200'
  return <span className={`ml-1.5 rounded-full px-2 py-0.5 text-[10px] font-semibold ring-1 ring-inset ${style}`}>{status}</span>
}
