'use client'

import { useState } from 'react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { stateName } from '@/lib/domain/states'
import { formatFullDate } from '@/lib/format'
import { requesterText, resolveRequester } from '@/components/app/route-formats'
import type { TripParticipant, TripRole } from '@/types/db'

/**
 * Re-order an EXPIRED permit from its card (2026-09-07, Task 75).
 *
 * Nash: "for all the expired permits, we should have also ability to request a
 * new permit from Synchron Permits. Any user, any member of the workspace
 * should have the power to request a new permit. And the person that's making
 * that request should be the one that's set as the client for that order."
 *
 * "when somebody clicks on that button… you will tell him that an order is
 * being sent to our trusted partner. They'll reach out via email for request
 * of additional information and the user making the request will be liable
 * for the payment for that permit."
 *
 * "if it's a broker does it, the broker has the power to choose who is going
 * to pay… This information will be delivered to our trusted partner, so they
 * know how they're gonna handle the billing."
 *
 * Shared by the workspace permit card and the driver's state section.
 */

export interface ReorderablePermit {
  id: string
  state_code: string
  permit_number: string | null
  expiration_date: string | null
}

export interface ExistingReorder {
  requested_by?: string | null
  requester_label?: string | null
  status: string
}

type Payer = 'broker' | 'carrier'

export function RequestNewPermitButton({
  tripId,
  permit,
  myRole,
  existing,
  participants,
  onDone,
  variant = 'workspace',
}: {
  tripId: string
  permit: ReorderablePermit
  myRole: TripRole | null
  /** A permit request that already re-orders this permit — shows who, hides the button. */
  existing?: ExistingReorder | null
  participants: TripParticipant[]
  onDone: () => void
  variant?: 'workspace' | 'driver'
}) {
  const [open, setOpen] = useState(false)
  const [payer, setPayer] = useState<Payer | null>(null)
  const [sending, setSending] = useState(false)

  if (!myRole) return null
  const state = stateName(permit.state_code)

  if (existing) {
    const who = resolveRequester(existing, participants)
    return (
      <span
        className={`font-semibold ${variant === 'driver' ? 'text-info' : 'text-blue-700'}`}
        title={`Sent to Synchron Permits · ${existing.status.replace('_', ' ')}`}
      >
        New permit requested by {requesterText(who)}
      </span>
    )
  }

  const isBroker = myRole === 'broker'
  const liability =
    isBroker && payer === 'carrier'
      ? 'The carrier is liable for payment for this permit.'
      : isBroker && payer === 'broker'
        ? 'You, as the broker, are liable for payment for this permit.'
        : 'You, as the person making this request, are liable for payment for this permit.'

  async function send() {
    if (isBroker && !payer) {
      toast.error('Choose who will pay Synchron Permits for this permit.')
      return
    }
    setSending(true)
    try {
      const res = await fetch(`/api/trips/${tripId}/requests`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type: 'permit_request',
          state_code: permit.state_code,
          replaces_permit_id: permit.id,
          ...(isBroker && payer ? { payer } : {}),
          notes: `Re-order of the expired ${state} permit${permit.permit_number ? ` ${permit.permit_number}` : ''}${
            permit.expiration_date ? ` (expired ${formatFullDate(permit.expiration_date)})` : ''
          }.`,
        }),
      })
      const json = await res.json().catch(() => ({}))
      if (!res.ok) {
        toast.error(json.error ?? 'Could not send the permit request')
        return
      }
      toast.success(`New ${state} permit ordered from our trusted partner Synchron Permits`)
      setOpen(false)
      setPayer(null)
      onDone()
    } finally {
      setSending(false)
    }
  }

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        className={
          variant === 'driver'
            ? 'rounded-lg border border-danger/40 bg-danger-bg px-2.5 py-1.5 text-[11px] font-bold text-danger hover:border-danger'
            : 'rounded-md border border-red-200 bg-red-50 px-2 py-0.5 text-[11px] font-bold text-red-700 transition hover:border-red-400'
        }
        title="Order a replacement permit from our trusted partner Synchron Permits"
      >
        Request new permit
      </button>

      <Dialog open={open} onOpenChange={(o) => !sending && setOpen(o)}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Order a new {state} permit</DialogTitle>
          </DialogHeader>
          <p className="text-xs text-neutral-500">
            {permit.permit_number && <span className="font-mono">{permit.permit_number} · </span>}
            {permit.expiration_date ? `Expired ${formatFullDate(permit.expiration_date)}` : 'Expired'}
          </p>

          {isBroker && (
            <fieldset className="space-y-1.5">
              <legend className="text-sm font-semibold">
                Who will pay Synchron Permits for this permit? <span className="text-red-600">*</span>
              </legend>
              {(
                [
                  ['broker', 'Broker pays'],
                  ['carrier', 'Carrier pays'],
                ] as const
              ).map(([value, label]) => (
                <label key={value} className="flex cursor-pointer items-center gap-2 text-sm">
                  <input
                    type="radio"
                    name="permit-payer"
                    checked={payer === value}
                    onChange={() => setPayer(value)}
                    className="accent-[#0f1b2d]"
                  />
                  {label}
                </label>
              ))}
            </fieldset>
          )}

          <p className="rounded-lg bg-neutral-50 p-3 text-sm leading-relaxed text-neutral-700">
            Your order is being sent to our trusted partner Synchron Permits. They will reach out by
            email if they need additional information. {liability}
          </p>
          <p className="text-[11px] leading-relaxed text-neutral-500">
            The order includes the trip commodity, overall dimensions, axle spacings, axle weights,
            truck and trailer information from My Unit, and the expired permit file.
          </p>

          <div className="flex justify-end gap-2">
            <Button variant="ghost" onClick={() => setOpen(false)} disabled={sending}>
              Cancel
            </Button>
            <Button onClick={send} disabled={sending} className="bg-[#0f1b2d] font-bold">
              {sending ? 'Sending…' : 'Send request'}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </>
  )
}
