"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { apiPost, apiPut } from "@/lib/api";
import { IntelligenceContextCard, IntelligenceIntakeBanner, buildIntelligenceNotes, getIntelligencePrefillPlan } from "@/components/crm/intelligence-intake";
import type { Shipper } from "@/types";

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);
}

const CRM_STAGES = [
  ["LEAD", "Lead"],
  ["CONTACTED", "Contacted"],
  ["WARM", "Warm"],
  ["HOT", "Hot"],
  ["ACTIVE_PARTNER", "Active Partner / Customer"],
  ["PREMIUM_PARTNER", "Premium Partner / Customer"],
  ["INACTIVE", "Inactive"],
  ["LOST", "Lost"],
] as const;

type ShipperFormValues = {
  companyName: string;
  contactName: string;
  phone: string;
  email: string;
  website: string;
  billingAddress: string;
  shippingNotes: string;
  billingNotes: string;
  notesText: string;
  crmStage: string;
  revenueIn: string;
  paymentsOut: string;
  lastContactedAt: string;
  nextFollowUpAt: string;
};

function makeInitialValues(record?: Shipper): ShipperFormValues {
  return {
    companyName: toStringValue(record?.companyName),
    contactName: toStringValue(record?.contactName),
    phone: toStringValue(record?.phone),
    email: toStringValue(record?.email),
    website: toStringValue(record?.website),
    billingAddress: toStringValue(record?.billingAddress),
    shippingNotes: toStringValue(record?.shippingNotes),
    billingNotes: toStringValue(record?.billingNotes),
    notesText: toStringValue(record?.notesText),
    crmStage: toStringValue(record?.crmStage || "LEAD"),
    revenueIn: toStringValue(record?.revenueIn),
    paymentsOut: toStringValue(record?.paymentsOut),
    lastContactedAt: toStringValue(record?.lastContactedAt).slice(0, 10),
    nextFollowUpAt: toStringValue(record?.nextFollowUpAt).slice(0, 10),
  };
}

function joinWithSpacing(existing: string, incoming: string) {
  return [existing.trim(), incoming.trim()].filter(Boolean).join(existing.trim() && incoming.trim() ? "\n\n" : "");
}

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 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 ?? ""}`} />; }
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 ?? ""}`} />; }

export function ShipperForm({ mode, shipper }: { mode: "create" | "edit"; shipper?: Shipper }) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const formRef = useRef<HTMLFormElement | null>(null);
  const [values, setValues] = useState<ShipperFormValues>(makeInitialValues(shipper));
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [didApplyIntelligencePrefill, setDidApplyIntelligencePrefill] = useState(false);
  const title = useMemo(() => (mode === "create" ? "Add shipper" : `Edit shipper ${shipper?.companyName ?? ""}`), [mode, shipper?.companyName]);

  const intelligenceBackHref = useMemo(() => {
    const params = new URLSearchParams();
    params.set("mode", searchParams.get("mode") || "market-search");
    const query = searchParams.get("query") || "";
    if (query.trim()) params.set("query", query.trim());
    return `/crm`;
  }, [searchParams]);

  const intelligenceIntakeActive = mode === "create" && searchParams.get("intake") === "intelligence";
  const intelligencePlan = useMemo(() => getIntelligencePrefillPlan(searchParams, "shipper"), [searchParams]);

  useEffect(() => {
    setValues(makeInitialValues(shipper));
    setDidApplyIntelligencePrefill(false);
  }, [shipper]);

  useEffect(() => {
    if (!intelligenceIntakeActive || didApplyIntelligencePrefill) return;
    const intakeName = searchParams.get("name")?.trim() || "";
    const lane = searchParams.get("lane")?.trim() || "";
    const location = searchParams.get("location")?.trim() || "";
    const whyItFits = searchParams.get("whyItFits")?.trim() || "";
    const nextMove = searchParams.get("nextMove")?.trim() || "";
    const contactHint = searchParams.get("contactHint")?.trim() || "";
    const locationLine = lane && location ? `Lane / location: ${lane} · ${location}` : lane || location;
    const shippingContext = [locationLine, whyItFits, nextMove, contactHint].filter(Boolean).join("\n\n");
    const researchNotes = buildIntelligenceNotes(searchParams);
    setValues((prev) => ({
      ...prev,
      companyName: intakeName || prev.companyName,
      crmStage: prev.crmStage === "LEAD" ? intelligencePlan.recommendedStage : prev.crmStage,
      nextFollowUpAt: prev.nextFollowUpAt || intelligencePlan.followUpDate,
      shippingNotes: joinWithSpacing(prev.shippingNotes, shippingContext),
      notesText: joinWithSpacing(prev.notesText, researchNotes),
    }));
    setDidApplyIntelligencePrefill(true);
  }, [didApplyIntelligencePrefill, intelligenceIntakeActive, intelligencePlan, searchParams]);

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

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    if (!values.companyName.trim()) {
      setError("Company name is required.");
      return;
    }
    setIsSubmitting(true);
    try {
      if (mode === "create") {
        const created = await apiPost<{ shipper: Shipper }>("/api/shippers", values);
        hardNavigate(`/shippers/${created.shipper.id}`);
        return;
      }
      if (shipper?.id) {
        await apiPut<{ shipper: Shipper }>(`/api/shippers/${shipper.id}`, values);
        hardNavigate(`/shippers/${shipper.id}`);
        return;
      }
      setError("Unable to save shipper.");
    } catch (err: any) {
      setError(err?.message ?? "Unable to save shipper.");
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <form ref={formRef} className="space-y-6" onSubmit={onSubmit}>
      {intelligenceIntakeActive ? (
        <IntelligenceIntakeBanner
          title="Saved lead notes are carrying into this form"
          subtitle="The lead name and notes were prefilled so you do not have to retype them."
          backHref={intelligenceBackHref}
        />
      ) : null}

      {intelligenceIntakeActive ? <IntelligenceContextCard params={searchParams} entityType="shipper" /> : null}

      <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">Keep shipper contacts, shipping instructions, money notes, and follow-up details in one place.</p>
      </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">Core details</h3>
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          <Field label="Company name *"><Input value={values.companyName} onChange={(e) => update("companyName", e.target.value)} /></Field>
          <Field label="Follow-up stage"><Select value={values.crmStage} onChange={(e) => update("crmStage", e.target.value)}>{CRM_STAGES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}</Select></Field>
          <Field label="Primary contact"><Input value={values.contactName} onChange={(e) => update("contactName", e.target.value)} /></Field>
          <Field label="Phone"><Input value={values.phone} onChange={(e) => update("phone", e.target.value)} /></Field>
          <Field label="Email"><Input type="email" value={values.email} onChange={(e) => update("email", e.target.value)} /></Field>
          <Field label="Website"><Input value={values.website} onChange={(e) => update("website", 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 notes</h3>
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
          <Field label="Money in"><Input inputMode="decimal" value={values.revenueIn} onChange={(e) => update("revenueIn", e.target.value)} /></Field>
          <Field label="Money out"><Input inputMode="decimal" value={values.paymentsOut} onChange={(e) => update("paymentsOut", e.target.value)} /></Field>
          <Field label="Last contacted"><Input type="date" value={values.lastContactedAt} onChange={(e) => update("lastContactedAt", e.target.value)} /></Field>
          <Field label="Next follow-up"><Input type="date" value={values.nextFollowUpAt} onChange={(e) => update("nextFollowUpAt", 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">Operational notes</h3>
        <div className="grid gap-4 xl:grid-cols-3">
          <Field label="Billing address"><TextArea rows={6} value={values.billingAddress} onChange={(e) => update("billingAddress", e.target.value)} /></Field>
          <Field label="Shipping notes"><TextArea rows={6} value={values.shippingNotes} onChange={(e) => update("shippingNotes", e.target.value)} /></Field>
          <Field label="Billing notes"><TextArea rows={6} value={values.billingNotes} onChange={(e) => update("billingNotes", e.target.value)} /></Field>
        </div>
        <div className="mt-4">
          <Field label="General 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={() => router.back()} className="rounded-xl border bg-white px-4 py-2 text-sm font-medium">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 shipper" : "Save changes"}</button>
      </div>
    </form>
  );
}
