"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 { Broker } 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);
}

type BrokerFormValues = {
  name: string;
  contactName: string;
  phone: string;
  email: string;
  billingNotes: string;
  factoringNotes: string;
  generalNotes: string;
};

function makeInitialValues(broker?: Broker): BrokerFormValues {
  return {
    name: toStringValue(broker?.name),
    contactName: toStringValue(broker?.contactName),
    phone: toStringValue(broker?.phone),
    email: toStringValue(broker?.email),
    billingNotes: toStringValue(broker?.billingNotes),
    factoringNotes: toStringValue(broker?.factoringNotes),
    generalNotes: toStringValue(broker?.generalNotes),
  };
}

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

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

  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, "broker"), [searchParams]);

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

  useEffect(() => {
    if (!intelligenceIntakeActive || didApplyIntelligencePrefill) return;
    const intakeName = searchParams.get("name")?.trim() || "";
    const nextMove = searchParams.get("nextMove")?.trim() || "";
    const researchNotes = buildIntelligenceNotes(searchParams);
    setValues((prev) => ({
      ...prev,
      name: intakeName || prev.name,
      billingNotes: joinWithSpacing(prev.billingNotes, nextMove),
      generalNotes: joinWithSpacing(prev.generalNotes, [intelligencePlan.summary, researchNotes].filter(Boolean).join("\n\n")),
    }));
    setDidApplyIntelligencePrefill(true);
  }, [didApplyIntelligencePrefill, intelligenceIntakeActive, intelligencePlan, searchParams]);

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

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    if (!values.name.trim()) {
      setError("Broker name is required.");
      return;
    }
    setIsSubmitting(true);
    try {
      if (mode === "create") {
        const created = await apiPost<{ broker: Broker }>("/api/brokers", values);
        hardNavigate(`/brokers/${created.broker.id}`);
        return;
      }
      if (broker?.id) {
        await apiPut<{ broker: Broker }>(`/api/brokers/${broker.id}`, values);
        hardNavigate(`/brokers/${broker.id}`);
        return;
      }
      setError("Unable to save broker.");
    } catch (err: any) {
      setError(err?.message ?? "Unable to save broker.");
    } 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="broker" /> : 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">Store broker contacts, billing guidance, and factoring notes.</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">
          <Field label="Broker name *"><Input value={values.name} onChange={(e) => update("name", e.target.value)} /></Field>
          <Field label="Contact name"><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>
        </div>
      </section>

      <section className="rounded-2xl border bg-white p-6 shadow-sm">
        <h3 className="mb-4 text-base font-semibold">Operations notes</h3>
        <div className="grid gap-4 xl:grid-cols-3">
          <Field label="Billing notes"><TextArea rows={6} value={values.billingNotes} onChange={(e) => update("billingNotes", e.target.value)} /></Field>
          <Field label="Factoring notes"><TextArea rows={6} value={values.factoringNotes} onChange={(e) => update("factoringNotes", e.target.value)} /></Field>
          <Field label="General notes"><TextArea rows={6} value={values.generalNotes} onChange={(e) => update("generalNotes", 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 broker" : "Save changes"}</button>
      </div>
    </form>
  );
}
