"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { useSearchParams } from "next/navigation";
import { apiGet, apiPost, apiPut } from "@/lib/api";
import { appendReturnTo, resolveReturnTo } from "@/src/modules/loads/load-navigation";
import type { Broker, Driver, Load, Truck } from "@/types";
import { AssignmentComplianceReadinessPanel } from "@/components/assignment-compliance-readiness-panel";
import { LoadsDocumentIntakePanel } from "@/components/loads-document-intake-panel";
import { LoadDocumentAccessPanel } from "@/components/load-document-access-panel";

function hardNavigate(path: string) {
  if (typeof window !== "undefined") {
    window.location.assign(`${path}${path.includes("?") ? "&" : "?"}refresh=${Date.now()}`);
  }
}

function toStringValue(value: unknown) {
  return value === null || value === undefined ? "" : String(value);
}

function toDateTimeLocal(value?: string | null) {
  if (!value) return "";
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return "";
  const pad = (n: number) => String(n).padStart(2, "0");
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

type LoadFormValues = {
  brokerId: string;
  truckId: string;
  driverId: string;
  status: string;
  rateConfirmationNumber: string;
  pickupLocation: string;
  deliveryLocation: string;
  pickupDate: string;
  deliveryDate: string;
  miles: string;
  invoiceAmount: string;
  dispatchFeeType: string;
  dispatchFeeRate: string;
  referenceNumber: string;
  specialRequirements: string;
  notesText: string;
};

function makeInitialValues(load?: Load): LoadFormValues {
  return {
    brokerId: toStringValue(load?.broker?.id),
    truckId: toStringValue(load?.truck?.id),
    driverId: toStringValue(load?.driver?.id),
    status: toStringValue(load?.status) || "DRAFT",
    rateConfirmationNumber: toStringValue(load?.rateConfirmationNumber),
    pickupLocation: toStringValue(load?.pickupLocation),
    deliveryLocation: toStringValue(load?.deliveryLocation),
    pickupDate: toDateTimeLocal(load?.pickupDate),
    deliveryDate: toDateTimeLocal(load?.deliveryDate),
    miles: toStringValue(load?.miles),
    invoiceAmount: toStringValue(load?.invoiceAmount),
    dispatchFeeType: toStringValue(load?.dispatchFeeType),
    dispatchFeeRate: toStringValue(load?.dispatchFeeRate),
    referenceNumber: toStringValue(load?.referenceNumber),
    specialRequirements: toStringValue(load?.specialRequirements),
    notesText: toStringValue(load?.notesText),
  };
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return <label className="block space-y-1"><span className="text-sm font-medium text-gray-700">{label}</span>{children}</label>;
}
function Input(props: React.InputHTMLAttributes<HTMLInputElement>) {
  return <input {...props} className={`w-full rounded-xl border px-3 py-2 text-sm outline-none focus:border-gray-400 ${props.className ?? ""}`} />;
}
function Select(props: React.SelectHTMLAttributes<HTMLSelectElement>) {
  return <select {...props} className={`w-full rounded-xl border bg-white px-3 py-2 text-sm outline-none focus:border-gray-400 ${props.className ?? ""}`} />;
}
function TextArea(props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) {
  return <textarea {...props} className={`w-full rounded-xl border px-3 py-2 text-sm outline-none focus:border-gray-400 ${props.className ?? ""}`} />;
}

export function LoadForm({ mode, load }: { mode: "create" | "edit"; load?: Load }) {
  const searchParams = useSearchParams();
  const formRef = useRef<HTMLFormElement | null>(null);
  const [values, setValues] = useState<LoadFormValues>(makeInitialValues(load));
  const [brokers, setBrokers] = useState<Broker[]>([]);
  const [trucks, setTrucks] = useState<Truck[]>([]);
  const [drivers, setDrivers] = useState<Driver[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const title = useMemo(() => (mode === "create" ? "Add load" : `Edit load ${load?.referenceNumber || load?.id || ""}`), [mode, load?.referenceNumber, load?.id]);
  const requestedReturnTo = searchParams.get("returnTo");
  const resolvedReturnTo = resolveReturnTo(requestedReturnTo, "/loads");

  useEffect(() => { setValues(makeInitialValues(load)); }, [load]);
  useEffect(() => {
    Promise.all([
      apiGet<{ brokers: Broker[] }>("/api/brokers"),
      apiGet<{ trucks: Truck[] }>("/api/trucks"),
      apiGet<{ drivers: Driver[] }>("/api/drivers"),
    ])
      .then(([brokerData, truckData, driverData]) => {
        setBrokers(brokerData.brokers.filter((b) => b.isActive !== false));
        setTrucks(truckData.trucks.filter((t) => t.isActive !== false));
        setDrivers(driverData.drivers.filter((d) => d.isActive !== false));
      })
      .catch((err) => setError(err?.message ?? "Failed to load assignment options"));
  }, []);

  function update<K extends keyof LoadFormValues>(key: K, value: LoadFormValues[K]) { setValues((prev) => ({ ...prev, [key]: value })); }

  const selectedDriver = useMemo(() => drivers.find((driver) => driver.id === values.driverId) || null, [drivers, values.driverId]);
  const selectedTruck = useMemo(() => trucks.find((truck) => truck.id === values.truckId) || null, [trucks, values.truckId]);
  const selectedBroker = useMemo(() => brokers.find((broker) => broker.id === values.brokerId) || null, [brokers, values.brokerId]);
  const draftLoadPreview = useMemo<Load>(() => ({
    id: load?.id || "draft-load-preview",
    status: values.status || "DRAFT",
    broker: selectedBroker ? { id: selectedBroker.id, name: selectedBroker.name, phone: selectedBroker.phone || null } : null,
    driver: selectedDriver ? { id: selectedDriver.id, firstName: selectedDriver.firstName, lastName: selectedDriver.lastName } : null,
    truck: selectedTruck ? { id: selectedTruck.id, truckNumber: selectedTruck.truckNumber } : null,
    pickupDate: values.pickupDate || null,
    deliveryDate: values.deliveryDate || null,
    pickupLocation: values.pickupLocation || null,
    deliveryLocation: values.deliveryLocation || null,
    referenceNumber: values.referenceNumber || null,
    rateConfirmationNumber: values.rateConfirmationNumber || null,
    invoiceAmount: values.invoiceAmount || null,
    specialRequirements: values.specialRequirements || null,
    notesText: values.notesText || null,
    payments: load?.payments || [],
    financialSummary: load?.financialSummary || null,
  }), [load?.financialSummary, load?.id, load?.payments, selectedBroker, selectedDriver, selectedTruck, values.deliveryDate, values.deliveryLocation, values.invoiceAmount, values.notesText, values.pickupDate, values.pickupLocation, values.rateConfirmationNumber, values.referenceNumber, values.specialRequirements, values.status]);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    if (!values.pickupLocation.trim() || !values.deliveryLocation.trim()) {
      setError("Pickup and delivery locations are required.");
      return;
    }
    setIsSubmitting(true);
    try {
      const payload = {
        ...values,
        brokerId: values.brokerId || undefined,
        truckId: values.truckId || undefined,
        driverId: values.driverId || undefined,
        pickupDate: values.pickupDate || undefined,
        deliveryDate: values.deliveryDate || undefined,
      };
      if (mode === "create") {
        const created = await apiPost<{ load: Load }>("/api/loads", payload);
        hardNavigate(appendReturnTo(`/loads/${created.load.id}`, requestedReturnTo));
        return;
      }
      if (load?.id) {
        await apiPut<{ load: Load }>(`/api/loads/${load.id}`, payload);
        hardNavigate(resolvedReturnTo);
        return;
      }
      setError("Unable to save load.");
    } catch (err: any) {
      setError(err?.message ?? "Unable to save load.");
    } finally {
      setIsSubmitting(false);
    }
  }

  return <form ref={formRef} className="space-y-6" onSubmit={onSubmit}>
    <div className="rounded-2xl border bg-white p-6 shadow-sm"><h2 className="text-lg font-semibold">{title}</h2><p className="mt-1 text-sm text-gray-500">Enter the broker, truck, driver, pickup, delivery, and rate. Keep notes short and clear.</p>{requestedReturnTo ? <div className="mt-3 rounded-xl border border-dashed bg-gray-50 px-3 py-3 text-xs text-gray-600"><div className="font-semibold text-gray-900">Save and return</div><div className="mt-1">After saving, you will return to the work area you came from.</div></div> : null}</div>
    {error ? <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div> : null}
    <section className="rounded-2xl border bg-white p-6 shadow-sm"><h3 className="mb-4 text-base font-semibold">Assignment</h3><div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
      <Field label="Broker"><Select value={values.brokerId} onChange={(e) => update("brokerId", e.target.value)}><option value="">Unassigned</option>{brokers.map((broker) => <option key={broker.id} value={broker.id}>{broker.name}</option>)}</Select></Field>
      <Field label="Truck"><Select value={values.truckId} onChange={(e) => update("truckId", e.target.value)}><option value="">Unassigned</option>{trucks.map((truck) => <option key={truck.id} value={truck.id}>{truck.truckNumber}</option>)}</Select></Field>
      <Field label="Driver"><Select value={values.driverId} onChange={(e) => update("driverId", e.target.value)}><option value="">Unassigned</option>{drivers.map((driver) => <option key={driver.id} value={driver.id}>{[driver.firstName, driver.lastName].filter(Boolean).join(" ") || driver.id}</option>)}</Select></Field>
      <Field label="Status"><Select value={values.status} onChange={(e) => update("status", e.target.value)}><option value="DRAFT">Draft</option><option value="ASSIGNED">Assigned</option><option value="IN_TRANSIT">In Transit</option><option value="DELIVERED">Delivered</option><option value="INVOICED">Invoiced</option><option value="PAID_FULL">Paid in full</option><option value="CANCELLED">Cancelled</option></Select></Field>
    </div></section>
    <details className="rounded-2xl border bg-white p-5 shadow-sm">
      <summary className="cursor-pointer list-none text-sm font-semibold text-slate-900">Show helpful checks</summary>
      <p className="mt-1 text-sm text-slate-500">Open these only when you need to check assignment or paperwork before saving.</p>
      <div className="mt-4 space-y-4">
        <AssignmentComplianceReadinessPanel load={draftLoadPreview} driver={selectedDriver} truck={selectedTruck} compact editHref={undefined} />
        <LoadsDocumentIntakePanel load={draftLoadPreview} compact />
        <LoadDocumentAccessPanel load={draftLoadPreview} driver={selectedDriver} truck={selectedTruck} compact />
      </div>
    </details>
    <section className="rounded-2xl border bg-white p-6 shadow-sm"><h3 className="mb-4 text-base font-semibold">Movement details</h3><div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
      <Field label="Pickup location *"><Input value={values.pickupLocation} onChange={(e) => update("pickupLocation", e.target.value)} /></Field>
      <Field label="Delivery location *"><Input value={values.deliveryLocation} onChange={(e) => update("deliveryLocation", e.target.value)} /></Field>
      <Field label="Reference number"><Input value={values.referenceNumber} onChange={(e) => update("referenceNumber", e.target.value)} /></Field>
      <Field label="Pickup date/time"><Input type="datetime-local" value={values.pickupDate} onChange={(e) => update("pickupDate", e.target.value)} /></Field>
      <Field label="Delivery date/time"><Input type="datetime-local" value={values.deliveryDate} onChange={(e) => update("deliveryDate", e.target.value)} /></Field>
      <Field label="Rate confirmation #"><Input value={values.rateConfirmationNumber} onChange={(e) => update("rateConfirmationNumber", e.target.value)} /></Field>
    </div></section>
    <section className="rounded-2xl border bg-white p-6 shadow-sm"><h3 className="mb-4 text-base font-semibold">Money</h3><div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
      <Field label="Base rate"><Input value={values.invoiceAmount} onChange={(e) => update("invoiceAmount", e.target.value)} /></Field>
      <Field label="Miles"><Input value={values.miles} onChange={(e) => update("miles", e.target.value)} /></Field>
      <Field label="Dispatch fee type"><Select value={values.dispatchFeeType} onChange={(e) => update("dispatchFeeType", e.target.value)}><option value="">Auto / none</option><option value="PERCENTAGE">Percentage</option><option value="FLAT_RATE">Flat rate</option></Select></Field>
      <Field label="Dispatch fee rate"><Input value={values.dispatchFeeRate} onChange={(e) => update("dispatchFeeRate", e.target.value)} /></Field>
    </div></section>
    <section className="rounded-2xl border bg-white p-6 shadow-sm"><h3 className="mb-4 text-base font-semibold">Requirements and notes</h3><div className="grid gap-4"><Field label="Special requirements"><TextArea rows={3} value={values.specialRequirements} onChange={(e) => update("specialRequirements", e.target.value)} /></Field><Field label="Internal notes"><TextArea rows={5} value={values.notesText} onChange={(e) => update("notesText", e.target.value)} /></Field></div></section>
    <div className="flex justify-end gap-3"><button type="button" onClick={() => hardNavigate(resolvedReturnTo)} className="rounded-xl border bg-white px-4 py-2 text-sm font-medium">{requestedReturnTo ? "Return to queue" : "Cancel"}</button><button type="submit" onClick={() => formRef.current?.requestSubmit()} disabled={isSubmitting} className="rounded-xl bg-black px-4 py-2 text-sm font-medium text-white disabled:opacity-60">{isSubmitting ? "Saving..." : mode === "create" ? "Add load" : "Save and return"}</button></div>
  </form>;
}
