'use client'

import { useState } from 'react'
import { toast } from 'sonner'
import { EXPENSE_CATEGORIES, expenseSummary, money, type ExpenseCategory, type ExpenseOwnerType } from '@/lib/domain/invoicing'
import { newId, useExpenses, type PilotExpense } from '@/lib/demo/invoicing-store'

/**
 * Expense tracking on a pilot assignment (article §13–§14, §25, §32).
 * "Expenses and receipts are private unless the user chooses to include them
 * on the invoice." The summary is the "basic report… what kind of expenses
 * that trip had" Nash asked for on 2026-09-12.
 */

const BLANK = {
  expenseDate: new Date().toISOString().slice(0, 10),
  category: 'Fuel' as ExpenseCategory,
  description: '',
  amount: '',
  receiptName: null as string | null,
  notes: '',
  billable: true,
  includeOnInvoice: false,
}

export function ExpenseTracker({
  assignmentId,
  tripRef,
  ownerType,
  ownerName,
  actorName,
  readOnly = false,
}: {
  assignmentId: string
  tripRef: string
  ownerType: ExpenseOwnerType
  ownerName: string
  actorName: string
  /** Free driver under a Pro company: can see, cannot manage (default pending confirmation). */
  readOnly?: boolean
}) {
  // Carrier truck drivers (Nash, 2026-09-13) track trip costs but have no
  // invoice tool — the invoice controls stay off for them.
  const forInvoice = ownerType !== 'carrier_driver'
  const noun = forInvoice ? 'assignment' : 'trip'
  const { expenses, save, remove } = useExpenses()
  const mine = expenses.filter((e) => e.assignmentId === assignmentId)
  const summary = expenseSummary(mine)
  const [adding, setAdding] = useState(false)
  const [form, setForm] = useState(BLANK)

  function submit() {
    const amount = parseFloat(form.amount)
    if (!form.category || !form.expenseDate || !Number.isFinite(amount) || amount <= 0) {
      toast.error('Category, date and a positive amount are required')
      return
    }
    const e: PilotExpense = {
      id: newId('exp'),
      assignmentId,
      tripRef,
      ownerType,
      ownerName,
      createdBy: actorName,
      category: form.category,
      description: form.description.trim(),
      amount,
      expenseDate: form.expenseDate,
      receiptName: form.receiptName,
      notes: form.notes.trim(),
      billable: form.billable,
      includeOnInvoice: form.includeOnInvoice,
      status: 'recorded',
      createdAt: new Date().toISOString(),
    }
    save(e)
    setForm(BLANK)
    setAdding(false)
    toast.success(`Expense saved to this ${noun} (preview — receipt bytes not stored)`)
  }

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <p className="text-[10px] font-bold uppercase tracking-[0.14em] text-slate-body/70">Expenses · {mine.length}</p>
        {!readOnly && (
          <button onClick={() => setAdding((v) => !v)} className="rounded-lg bg-navy-900 px-3 py-1.5 text-xs font-bold text-white hover:bg-navy-800">
            {adding ? 'Cancel' : '+ Add Expense'}
          </button>
        )}
      </div>

      {adding && (
        <div className="grid gap-2 rounded-2xl border border-line bg-white p-4 sm:grid-cols-2">
          <label className="text-xs">
            <span className="text-slate-body">Expense date</span>
            <input type="date" value={form.expenseDate} onChange={(e) => setForm({ ...form, expenseDate: e.target.value })} className="mt-1 w-full rounded-lg border border-line px-2.5 py-1.5" />
          </label>
          <label className="text-xs">
            <span className="text-slate-body">Category</span>
            <select value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value as ExpenseCategory })} className="mt-1 w-full rounded-lg border border-line bg-white px-2.5 py-1.5">
              {EXPENSE_CATEGORIES.map((c) => <option key={c}>{c}</option>)}
            </select>
          </label>
          <label className="text-xs sm:col-span-2">
            <span className="text-slate-body">Description</span>
            <input value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} className="mt-1 w-full rounded-lg border border-line px-2.5 py-1.5" placeholder="e.g. Diesel, Pilot truck stop exit 110" />
          </label>
          <label className="text-xs">
            <span className="text-slate-body">Amount (USD)</span>
            <input type="number" min="0" step="0.01" value={form.amount} onChange={(e) => setForm({ ...form, amount: e.target.value })} className="mt-1 w-full rounded-lg border border-line px-2.5 py-1.5" />
          </label>
          <label className="text-xs">
            <span className="text-slate-body">Receipt / photo</span>
            <input type="file" accept="image/*,application/pdf" onChange={(e) => setForm({ ...form, receiptName: e.target.files?.[0]?.name ?? null })} className="mt-1 w-full text-[11px]" />
            {form.receiptName && <span className="mt-0.5 block text-[11px] text-slate-body">Attached: {form.receiptName}</span>}
          </label>
          <label className="text-xs sm:col-span-2">
            <span className="text-slate-body">Notes</span>
            <input value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} className="mt-1 w-full rounded-lg border border-line px-2.5 py-1.5" />
          </label>
          <label className="flex items-center gap-2 text-xs"><input type="checkbox" checked={form.billable} onChange={(e) => setForm({ ...form, billable: e.target.checked })} /> Billable to customer</label>
          {forInvoice && <label className="flex items-center gap-2 text-xs"><input type="checkbox" checked={form.includeOnInvoice} onChange={(e) => setForm({ ...form, includeOnInvoice: e.target.checked })} /> Include on invoice</label>}
          <p className="text-[11px] text-slate-body sm:col-span-2">{forInvoice ? 'Expenses and receipts stay private unless you include them on the invoice.' : 'Expenses and receipts are private to you — nobody else on the trip sees them.'}</p>
          <button onClick={submit} className="rounded-lg bg-amber-brand py-2 text-xs font-bold text-navy-950 hover:bg-amber-deep sm:col-span-2">Save expense</button>
        </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 expenses on this {noun} yet.</p>
      ) : (
        <div className="divide-y divide-line rounded-2xl border border-line bg-white">
          {mine.map((e) => (
            <div key={e.id} className="flex flex-wrap items-center justify-between gap-2 px-4 py-2.5 text-xs">
              <div>
                <p className="font-semibold">{e.category}{e.description ? ` · ${e.description}` : ''}</p>
                <p className="text-slate-body">
                  {e.expenseDate}{e.receiptName ? ` · 📎 ${e.receiptName}` : ''}{e.notes ? ` · ${e.notes}` : ''}
                </p>
                <p className="text-[11px] text-slate-body">
                  {e.billable ? 'Billable' : 'Not billable'}{forInvoice ? ` · ${e.includeOnInvoice ? 'On invoice' : 'Private'}` : ''} · by {e.createdBy}
                </p>
              </div>
              <div className="flex items-center gap-2">
                <span className="font-bold">{money(e.amount)}</span>
                {!readOnly && (
                  <>
                    {forInvoice && (
                      <button onClick={() => save({ ...e, includeOnInvoice: !e.includeOnInvoice })} className="rounded-lg border border-line px-2 py-1 text-[11px] font-semibold text-slate-body hover:text-ink">
                        {e.includeOnInvoice ? 'Remove from invoice' : 'Include on invoice'}
                      </button>
                    )}
                    <button onClick={() => remove(e.id)} className="text-[11px] font-semibold text-slate-body hover:text-danger">Delete</button>
                  </>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {mine.length > 0 && (
        <div className="rounded-2xl border border-line bg-paper p-4 text-xs">
          <p className="text-[10px] font-bold uppercase tracking-[0.14em] text-slate-body/70">Expense summary — this trip</p>
          <div className="mt-2 grid gap-1 sm:grid-cols-2">
            {summary.byCategory.map((c) => (
              <div key={c.category} className="flex justify-between"><span>{c.category} <span className="text-slate-body">× {c.count}</span></span><span className="font-semibold">{money(c.total)}</span></div>
            ))}
          </div>
          <div className="mt-2 grid gap-1 border-t border-line pt-2 sm:grid-cols-3">
            <div className="flex justify-between"><span>Total</span><span className="font-bold">{money(summary.total)}</span></div>
            <div className="flex justify-between"><span>Billable</span><span className="font-semibold">{money(summary.billable)}</span></div>
            {forInvoice && <div className="flex justify-between"><span>On invoice</span><span className="font-semibold">{money(summary.onInvoice)}</span></div>}
          </div>
        </div>
      )}
    </div>
  )
}
