'use client'

import { useState } from 'react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { formatInches, formatWeight } from '@/lib/format'

/**
 * Editable dimensions section, shared by the trip workspace and the driver
 * view (per the client meeting these are DIFFERENT things and both must show):
 *   "Load"               → load_* columns (the commodity itself)
 *   "Overall Dimensions" → overall_* columns (truck + trailer combo — what
 *                          permits are cross-checked against)
 * The AI-extracted values are a starting point; broker, carrier, and (per the
 * driver feedback) the driver can correct them — every change is recorded in
 * trip history so it stays transparent to everyone on the trip.
 */
export function DimensionsEditor({
  title,
  tripId,
  prefix,
  values,
  note,
  canEdit,
  onSaved,
}: {
  title: string
  tripId: string
  prefix: 'load' | 'overall'
  values: { length: number | null; width: number | null; height: number | null; weight: number | null }
  note?: string
  canEdit: boolean
  onSaved: () => void
}) {
  const [editing, setEditing] = useState(false)
  const [saving, setSaving] = useState(false)
  const toFt = (v: number | null) => (v == null ? '' : String(Math.floor(v / 12)))
  const toIn = (v: number | null) => (v == null ? '' : String(v % 12))
  const buildForm = () => ({
    lengthFt: toFt(values.length),
    lengthIn: toIn(values.length),
    widthFt: toFt(values.width),
    widthIn: toIn(values.width),
    heightFt: toFt(values.height),
    heightIn: toIn(values.height),
    weight: values.weight == null ? '' : String(values.weight),
  })
  const [form, setForm] = useState(buildForm)

  // Rebuild from the latest values on every edit start — the same dimensions
  // can be edited from more than one place (workspace, driver header, My
  // Unit), so a form snapshotted at mount could silently revert a newer save.
  function startEditing() {
    setForm(buildForm())
    setEditing(true)
  }

  function inches(ft: string, inch: string): number | null {
    if (ft.trim() === '' && inch.trim() === '') return null
    const f = Number(ft || 0)
    const i = Number(inch || 0)
    if (!Number.isFinite(f) || !Number.isFinite(i) || f < 0 || i < 0) return null
    return Math.round(f * 12 + i)
  }

  async function save() {
    setSaving(true)
    try {
      const res = await fetch(`/api/trips/${tripId}/dimensions`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          [`${prefix}_length_in`]: inches(form.lengthFt, form.lengthIn),
          [`${prefix}_width_in`]: inches(form.widthFt, form.widthIn),
          [`${prefix}_height_in`]: inches(form.heightFt, form.heightIn),
          [`${prefix}_weight_lbs`]: form.weight.trim() === '' ? null : Math.round(Number(form.weight)),
        }),
      })
      const json = await res.json()
      if (!res.ok) {
        toast.error(json.error ?? 'Could not save dimensions')
        return
      }
      toast.success(
        json.dimension_warnings > 0
          ? `Saved — ${json.dimension_warnings} permit dimension warning${json.dimension_warnings === 1 ? '' : 's'} found`
          : 'Saved — all permits check out',
      )
      setEditing(false)
      onSaved()
    } finally {
      setSaving(false)
    }
  }

  const set = (k: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) =>
    setForm((f) => ({ ...f, [k]: e.target.value }))

  return (
    <div className="mt-4">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-bold uppercase tracking-wide text-neutral-500">{title}</h3>
        {canEdit && !editing && (
          <Button size="sm" variant="outline" onClick={startEditing}>
            Edit
          </Button>
        )}
      </div>

      {!editing ? (
        <dl className="mt-3 grid grid-cols-2 gap-3 text-sm">
          <DimField label="Length" value={formatInches(values.length)} />
          <DimField label="Width" value={formatInches(values.width)} />
          <DimField label="Height" value={formatInches(values.height)} />
          <DimField label="Weight" value={formatWeight(values.weight)} />
        </dl>
      ) : (
        <div className="mt-3 space-y-3">
          {(
            [
              ['Length', 'lengthFt', 'lengthIn'],
              ['Width', 'widthFt', 'widthIn'],
              ['Height', 'heightFt', 'heightIn'],
            ] as const
          ).map(([label, ftKey, inKey]) => (
            <div key={label} className="flex items-center gap-2">
              <span className="w-16 text-xs font-bold uppercase text-neutral-400">{label}</span>
              <Input
                type="number"
                min={0}
                value={form[ftKey]}
                onChange={set(ftKey)}
                placeholder="0"
                className="w-20"
              />
              <span className="text-xs text-neutral-500">ft</span>
              <Input
                type="number"
                min={0}
                max={11}
                value={form[inKey]}
                onChange={set(inKey)}
                placeholder="0"
                className="w-20"
              />
              <span className="text-xs text-neutral-500">in</span>
            </div>
          ))}
          <div className="flex items-center gap-2">
            <span className="w-16 text-xs font-bold uppercase text-neutral-400">Weight</span>
            <Input
              type="number"
              min={0}
              value={form.weight}
              onChange={set('weight')}
              placeholder="0"
              className="w-32"
            />
            <span className="text-xs text-neutral-500">lbs</span>
          </div>
          <div className="flex gap-2 pt-1">
            <Button size="sm" onClick={save} disabled={saving}>
              {saving ? 'Saving…' : 'Save & re-check permits'}
            </Button>
            <Button size="sm" variant="ghost" onClick={() => setEditing(false)} disabled={saving}>
              Cancel
            </Button>
          </div>
        </div>
      )}
      {note && <p className="mt-2 text-[11px] text-neutral-400">{note}</p>}
    </div>
  )
}

function DimField({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-lg bg-neutral-50 p-2.5">
      <dt className="text-[10px] font-bold uppercase tracking-wide text-neutral-400">{label}</dt>
      <dd className="mt-0.5 font-medium">{value}</dd>
    </div>
  )
}
