"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { useParams } from "next/navigation";
import { apiGet, apiPost } from "@/lib/api";
import type { Broker } from "@/types";
import { PageHeader } from "@/components/ui/page-header";
import { CRMActivityTimeline } from "@/src/modules/crm-activities/components/crm-activity-timeline";
import { CRMStageControls } from "@/src/modules/crm-activities/components/crm-stage-controls";
import { CrmDetailActionBar } from "@/components/crm/crm-detail-action-bar";
import { appendReturnTo, CrmReturnHeader, CrmSummaryStrip, useCrmReturnTo } from "@/components/crm/crm-navigation";
import { AssignmentPanel } from "@/components/crm/assignment-panel";
import { OnboardingPaperworkPanel } from "@/components/crm/onboarding-readiness-panel";
import { IntelligenceDecisionSupportCard, IntelligenceDetailReviewBanner, buildIntelligenceCreateHref, getIntelligenceParamsFromHref } from "@/components/crm/intelligence-intake";
import { CrmDetailWorkspaceContinuity } from "@/components/crm/crm-detail-workspace-continuity";
import { QuoteCallContinuity } from "@/components/crm/quote-call-continuity";
import { CallNoteContinuity } from "@/components/crm/call-note-continuity";

function money(value?: string | null) {
  if (!value) return "-";
  const num = Number(value);
  if (Number.isNaN(num)) return value;
  return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(num);
}

function dateValue(value?: string | null) {
  return value ? new Date(value).toLocaleDateString() : "-";
}

function Card({ title, children }: { title: string; children: React.ReactNode }) {
  return <section className="rounded-2xl border bg-white p-6 shadow-sm"><h2 className="mb-4 text-base font-semibold">{title}</h2>{children}</section>;
}

function Row({ label, value }: { label: string; value?: React.ReactNode }) {
  return <div className="grid grid-cols-1 gap-1 border-b py-3 last:border-b-0 md:grid-cols-[180px_1fr] md:gap-4"><div className="text-sm font-medium text-gray-500">{label}</div><div className="text-sm text-gray-900">{value || "-"}</div></div>;
}

export default function BrokerDetailPage() {
  const params = useParams<{ id: string }>();
  const [broker, setBroker] = useState<Broker | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [working, setWorking] = useState(false);
  const { currentReturnTo, listHref } = useCrmReturnTo("/brokers");
  const intelligenceParams = useMemo(() => getIntelligenceParamsFromHref(listHref), [listHref]);
  const intelligenceCreateHref = useMemo(() => {
    if (!intelligenceParams) return `/brokers/new`;
    return buildIntelligenceCreateHref({
      source: "intelligence",
      entityType: "broker",
      name: intelligenceParams.get("name") || "",
      lane: intelligenceParams.get("lane") || undefined,
      location: intelligenceParams.get("location") || undefined,
      whyItFits: intelligenceParams.get("whyItFits") || undefined,
      nextMove: intelligenceParams.get("nextMove") || undefined,
      crmFit: intelligenceParams.get("crmFit") || undefined,
      contactHint: intelligenceParams.get("contactHint") || undefined,
      query: intelligenceParams.get("query") || undefined,
      mode: intelligenceParams.get("mode") || undefined,
    });
  }, [intelligenceParams]);

  useEffect(() => {
    if (!params?.id) return;
    apiGet<{ broker: Broker }>(`/api/brokers/${params.id}`)
      .then((data) => setBroker(data.broker))
      .catch((e) => setError(e?.message ?? "Failed to load broker"));
  }, [params?.id]);

  async function reloadRecord() {
    if (!params?.id) return;
    const refreshed = await apiGet<{ broker: Broker }>(`/api/brokers/${params.id}`);
    setBroker(refreshed.broker);
  }

  async function toggleActive() {
    if (!broker) return;
    try {
      setWorking(true);
      await apiPost(`/api/brokers/${broker.id}/${broker.isActive === false ? "reactivate" : "deactivate"}`, {});
      await reloadRecord();
    } catch (e: any) {
      setError(e?.message ?? "Unable to update broker state");
    } finally {
      setWorking(false);
    }
  }

  if (error) return <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>;
  if (!broker) return <div className="text-sm text-gray-500">Loading broker...</div>;

  const onboardingChecklist = [
    { key: "contact-name", label: "Primary contact name", complete: Boolean(broker.contactName), helpText: "A named broker-side contact keeps check calls, rate follow-up, and issue resolution from stalling." },
    { key: "phone", label: "Direct phone", complete: Boolean(broker.phone), helpText: "Dispatch needs a reachable phone number for urgent pickup, delivery, and detention coordination." },
    { key: "email", label: "Primary email", complete: Boolean(broker.email), helpText: "Billing, load tenders, and paperwork follow-up depend on a working broker email." },
    { key: "billing-notes", label: "Billing guidance", complete: Boolean(broker.billingNotes), helpText: "Carrier pay, factoring, and invoice handling improve when billing instructions are captured early." },
    { key: "follow-up", label: "Next follow-up date", complete: Boolean(broker.nextFollowUpAt), helpText: "An onboarding next-step date helps stop warm broker relationships from going stale." },
  ];

  const brokerContactPrompts = [
    broker.phone
      ? { key: "phone-ready", label: "Phone ready", tone: "READY" as const, body: "Dispatch can call this broker directly when a load needs attention." }
      : { key: "phone-missing", label: "Phone missing", tone: "ACTION" as const, body: "Add a direct broker phone number before using this record for urgent load work." },
    broker.email
      ? { key: "email-ready", label: "Email lane ready", tone: "READY" as const, body: "This broker record is ready for rate confirmations, invoice follow-up, and paperwork requests by email." }
      : { key: "email-missing", label: "Email lane missing", tone: "ACTION" as const, body: "Capture a broker email so invoices, confirmations, and POD follow-up have a durable contact path." },
    broker.contactName
      ? { key: "owner-ready", label: "Named owner present", tone: "READY" as const, body: `Primary broker contact is ${broker.contactName}, which improves ownership during onboarding and issue handling.` }
      : { key: "owner-missing", label: "Named owner missing", tone: "WATCH" as const, body: "This broker record has communication channels but no named owner. Add one before high-value load volume ramps up." },
  ];

  const brokerOnboardingPrompts = [
    broker.billingNotes
      ? { key: "billing-ready", label: "Billing handling documented", tone: "READY" as const, body: "Billing instructions are already captured for this broker." }
      : { key: "billing-missing", label: "Billing handling not documented", tone: "ACTION" as const, body: "Capture invoice destination, paperwork expectations, and payment handling notes before dispatch volume increases." },
    broker.factoringNotes
      ? { key: "factoring-ready", label: "Factoring notes present", tone: "READY" as const, body: "Factoring-related broker behavior has been documented for the team." }
      : { key: "factoring-watch", label: "Factoring notes still open", tone: "WATCH" as const, body: "If this broker requires special factoring handling, note it now so accounting and dispatch stay aligned." },
    broker.loads?.length
      ? { key: "history-ready", label: "Broker already linked to loads", tone: "READY" as const, body: "This broker already has operating history in the system, which helps onboarding confidence." }
      : { key: "history-watch", label: "No work history yet", tone: "WATCH" as const, body: "This broker has no linked loads yet. Review contact and billing details before first use." },
  ];

  return (
    <div className="space-y-6">
      <PageHeader title={broker.name} subtitle="Broker record, contact details, notes, and recent loads." />

      {intelligenceParams ? (
        <>
        <IntelligenceDetailReviewBanner
          params={intelligenceParams}
          entityType="broker"
          recordName={broker.name}
          listHref={listHref}
          createHref={intelligenceCreateHref}
        />
        <IntelligenceDecisionSupportCard
          params={intelligenceParams}
          entityType="broker"
          recordName={broker.name}
          recordLocation={broker.generalNotes}
          useExistingHref={appendReturnTo(`${currentReturnTo}#lifecycle-controls`, currentReturnTo)}
          createHref={intelligenceCreateHref}
        />
        </>
      ) : null}

      <CrmReturnHeader
        listHref={listHref}
        listLabel="brokers"
        editHref={appendReturnTo(`/brokers/${broker.id}/edit`, currentReturnTo)}
        editLabel="Edit Broker"
        stage={broker.crmStage}
        isActive={broker.isActive}
      />



      <details className="group rounded-3xl border border-slate-200 bg-white shadow-sm">
        <summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-5 py-4">
          <div>
            <div className="text-sm font-semibold text-slate-900">Broker quick path</div>
            <div className="mt-1 text-xs text-slate-500">Open for return links, setup facts, and jump links. The main page stays focused on the record.</div>
          </div>
          <span className="rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 text-[11px] font-medium text-slate-600 group-open:hidden">Show</span>
          <span className="hidden rounded-full border border-slate-200 bg-slate-900 px-2.5 py-1 text-[11px] font-medium text-white group-open:inline-flex">Hide</span>
        </summary>
        <div className="space-y-5 border-t border-slate-200 px-5 py-5">
      <CrmDetailWorkspaceContinuity
        currentHref="/brokers"
        listHref={listHref}
        listLabel="brokers"
        createHref={intelligenceCreateHref}
        createLabel="Create Broker"
        title="Broker profile"
        subtitle="Key broker identity, reachability, follow-up timing, and recent operating context stay visible before you scroll into deeper controls."
        continuityLabel={broker.nextFollowUpAt ? "Follow-up scheduled" : broker.email && broker.phone ? "Contact lanes ready" : "Needs profile cleanup"}
        continuityTone={broker.nextFollowUpAt ? "good" : broker.email && broker.phone ? "watch" : "action"}
        facts={[
          { label: "Primary contact", value: broker.contactName || broker.email || "-" },
          { label: "Last contacted", value: dateValue(broker.lastContactedAt) },
          { label: "Next follow-up", value: dateValue(broker.nextFollowUpAt) },
          { label: "Recent loads", value: broker.loads?.length ?? 0 },
        ]}
        sectionLinks={[
          { href: "#broker-profile", label: "Profile" },
          { href: "#recent-loads", label: "Recent loads" },
          { href: "#lifecycle-controls", label: "Follow-up" },
          { href: "#crm-timeline", label: "Timeline" },
        ]}
      />
        </div>
      </details>


      <CrmDetailActionBar
        primaryActions={[
          { href: listHref, label: "Back to Brokers" },
          { href: appendReturnTo(`/brokers/${broker.id}/edit`, currentReturnTo), label: "Edit Broker", tone: "primary" },
          ...(broker.phone ? [{ href: `/cori/quotes`, label: "Call Broker", popupContext: { source: "brokers", contactId: broker.id, contactType: "broker", contactName: broker.contactName || broker.name, phone: broker.phone || undefined, companyLabel: broker.name, purpose: "NEGOTIATE_RATE" } }] : []),
          ...(broker.phone ? [{ href: `/cori/quotes?source=brokers&brokerId=${broker.id}&contactName=${encodeURIComponent(broker.contactName || broker.name)}&phone=${encodeURIComponent(broker.phone || "")}&companyLabel=${encodeURIComponent(broker.name)}&purpose=NEGOTIATE_RATE&returnTo=${encodeURIComponent(currentReturnTo)}`, label: "Call" }] : []),
          ...(broker.email ? [{ href: `mailto:${broker.email}`, label: "Email Broker" }] : []),
        ]}
        jumpActions={[
          { href: "#lifecycle-controls", label: "Follow-up controls" },
          { href: "#crm-timeline", label: "Activity history" },
          { href: "#recent-loads", label: "Recent Loads" },
        ]}
        stateAction={{
          label: working ? "Working..." : broker.isActive === false ? "Reactivate Broker" : "Deactivate Broker",
          tone: broker.isActive === false ? "default" : "danger",
          disabled: working,
          onClick: toggleActive,
        }}
      />

      <CrmSummaryStrip
        items={[
          { label: "Primary contact", value: broker.contactName || broker.email || "-" },
          { label: "Last contacted", value: dateValue(broker.lastContactedAt) },
          { label: "Next follow-up", value: dateValue(broker.nextFollowUpAt) },
          { label: "Open loads", value: broker.loads?.length ?? 0 },
        ]}
      />


      <details className="group rounded-3xl border border-slate-200 bg-white shadow-sm">
        <summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-5 py-4">
          <div>
            <div className="text-sm font-semibold text-slate-900">Call notes and call setup</div>
            <div className="mt-1 text-xs text-slate-500">Open only when you need saved call notes or call details.</div>
          </div>
          <span className="rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 text-[11px] font-medium text-slate-600 group-open:hidden">Show</span>
          <span className="hidden rounded-full border border-slate-200 bg-slate-900 px-2.5 py-1 text-[11px] font-medium text-white group-open:inline-flex">Hide</span>
        </summary>
        <div className="space-y-5 border-t border-slate-200 px-5 py-5">
      {(broker.phone) ? (
        <QuoteCallContinuity
          phone={broker.phone}
          contactName={broker.contactName || broker.name}
          launchHref={`/cori/quotes?source=brokers&brokerId=${broker.id}&contactName=${encodeURIComponent(broker.contactName || broker.name)}&phone=${encodeURIComponent(broker.phone || "")}&returnTo=${encodeURIComponent(currentReturnTo)}`}
        />
      ) : null}

      <CallNoteContinuity
        entityType="broker"
        entityId={broker.id}
        entityName={broker.name}
        contactName={broker.contactName || broker.name}
        phoneNumber={broker.phone}
      />
        </div>
      </details>

      <div id="broker-profile" className="grid gap-6 xl:grid-cols-2">
        <Card title="Broker summary">
          <Row label="Broker name" value={broker.name} />
          <Row label="Primary contact" value={broker.contactName} />
          <Row label="Phone" value={broker.phone} />
          <Row label="Email" value={broker.email ? <a href={`mailto:${broker.email}`} className="hover:underline">{broker.email}</a> : "-"} />
          <Row label="Website" value={broker.website ? <a href={broker.website} target="_blank" rel="noreferrer" className="hover:underline">{broker.website}</a> : "-"} />
          <Row label="Revenue In" value={money(broker.revenueIn)} />
          <Row label="Payments Out" value={money(broker.paymentsOut)} />
        </Card>
        <div id="operational-notes" className="scroll-mt-24"><Card title="Operational notes">
          <Row label="Billing notes" value={broker.billingNotes} />
          <Row label="Factoring notes" value={broker.factoringNotes} />
          <Row label="General notes" value={broker.generalNotes} />
        </Card>
      </div>
      </div>

      <div id="recent-loads" className="scroll-mt-24">
        <Card title="Recent loads">
          {broker.loads?.length ? (
            <div className="overflow-hidden rounded-xl border">
              <table className="min-w-full divide-y">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Status</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Pickup</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Delivery</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Truck</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Revenue</th>
                  </tr>
                </thead>
                <tbody className="divide-y bg-white">
                  {broker.loads.map((load) => (
                    <tr key={load.id}>
                      <td className="px-4 py-3 text-sm">{load.status}</td>
                      <td className="px-4 py-3 text-sm">{load.pickupLocation || "-"}</td>
                      <td className="px-4 py-3 text-sm">{load.deliveryLocation || "-"}</td>
                      <td className="px-4 py-3 text-sm">{load.truck?.truckNumber || "-"}</td>
                      <td className="px-4 py-3 text-sm">{money(load.invoiceAmount)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : <div className="text-sm text-gray-500">No recent loads linked to this broker.</div>}
        </Card>
      </div>


      <details className="group rounded-3xl border border-slate-200 bg-white shadow-sm">
        <summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-5 py-4">
          <div>
            <div className="text-sm font-semibold text-slate-900">Broker setup checks</div>
            <div className="mt-1 text-xs text-slate-500">Open only when checking setup, follow-up, or history.</div>
          </div>
          <span className="rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 text-[11px] font-medium text-slate-600 group-open:hidden">Show</span>
          <span className="hidden rounded-full border border-slate-200 bg-slate-900 px-2.5 py-1 text-[11px] font-medium text-white group-open:inline-flex">Hide</span>
        </summary>
        <div className="space-y-5 border-t border-slate-200 px-5 py-5">
      <OnboardingPaperworkPanel
        entityLabel="broker"
        editHref={appendReturnTo(`/brokers/${broker.id}/edit`, currentReturnTo)}
        checklist={onboardingChecklist}
        contactPrompts={brokerContactPrompts}
        onboardingPrompts={brokerOnboardingPrompts}
      />

      <AssignmentPanel targetType="BROKER" targetId={broker.id} targetLabel="broker" />

      <div id="lifecycle-controls" className="scroll-mt-24">
        <CRMStageControls
          endpoint={`/api/brokers/${broker.id}`}
          currentStage={broker.crmStage}
          lastContactedAt={broker.lastContactedAt}
          nextFollowUpAt={broker.nextFollowUpAt}
          onUpdated={reloadRecord}
        />
      </div>
      <div id="crm-timeline" className="scroll-mt-24">
        <CRMActivityTimeline entityType="BROKER" entityId={broker.id} />
      </div>
        </div>
      </details>
    </div>
  );
}
