"use client";

import { useEffect, useMemo, useState } from "react";
import { useParams } from "next/navigation";
import { apiGet, apiPost } from "@/lib/api";
import type { Shipper } from "@/types";
import { CRMStageControls } from "@/src/modules/crm-activities/components/crm-stage-controls";
import { PageHeader } from "@/components/ui/page-header";
import { CRMActivityTimeline } from "@/src/modules/crm-activities/components/crm-activity-timeline";
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 ShipperDetailPage() {
  const params = useParams<{ id: string }>();
  const [shipper, setShipper] = useState<Shipper | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [working, setWorking] = useState(false);
  const { currentReturnTo, listHref } = useCrmReturnTo("/shippers");
  const intelligenceParams = useMemo(() => getIntelligenceParamsFromHref(listHref), [listHref]);
  const intelligenceCreateHref = useMemo(() => {
    if (!intelligenceParams) return `/shippers/new`;
    return buildIntelligenceCreateHref({
      source: "intelligence",
      entityType: "shipper",
      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<{ shipper: Shipper }>(`/api/shippers/${params.id}`)
      .then((data) => setShipper(data.shipper))
      .catch((e) => setError(e?.message ?? "Failed to load shipper"));
  }, [params?.id]);

  async function reloadRecord() {
    if (!params?.id) return;
    const data = await apiGet<{ shipper: Shipper }>(`/api/shippers/${params.id}`);
    setShipper(data.shipper);
  }

  async function toggleActive() {
    if (!shipper) return;
    try {
      setWorking(true);
      await apiPost(`/api/shippers/${shipper.id}/${shipper.isActive === false ? "reactivate" : "deactivate"}`, {});
      await reloadRecord();
    } catch (e: any) {
      setError(e?.message ?? "Unable to update shipper 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 (!shipper) return <div className="text-sm text-gray-500">Loading shipper...</div>;

  const onboardingChecklist = [
    { key: "company-name", label: "Company name", complete: Boolean(shipper.companyName), helpText: "A shipper record should carry the actual customer company name before it is treated as onboarding-ready." },
    { key: "contact-name", label: "Primary contact", complete: Boolean(shipper.contactName), helpText: "A named shipper-side owner reduces pickup and billing confusion once loads begin moving." },
    { key: "phone", label: "Direct phone", complete: Boolean(shipper.phone), helpText: "Dispatch needs a direct shipper phone number for live pickup and exception handling." },
    { key: "email", label: "Primary email", complete: Boolean(shipper.email), helpText: "A shipper email is needed for confirmations, billing communication, and paperwork follow-up." },
    { key: "shipping-notes", label: "Shipping notes", complete: Boolean(shipper.shippingNotes), helpText: "Pickup constraints, dock rules, or appointment expectations should be documented before first-load execution." },
    { key: "billing-address", label: "Billing address", complete: Boolean(shipper.billingAddress), helpText: "Billing destination details help avoid delays once invoicing begins." },
  ];

  const shipperContactPrompts = [
    shipper.contactName
      ? { key: "contact-ready", label: "Named shipper contact ready", tone: "READY" as const, body: `Primary contact is ${shipper.contactName}, which gives dispatch a direct human owner for this account.` }
      : { key: "contact-missing", label: "Named shipper contact missing", tone: "ACTION" as const, body: "Add a named shipper contact before using this account for active client onboarding." },
    shipper.phone
      ? { key: "phone-ready", label: "Phone lane ready", tone: "READY" as const, body: "This shipper record is ready for urgent call-based pickup coordination." }
      : { key: "phone-missing", label: "Phone missing", tone: "ACTION" as const, body: "Capture a direct shipper phone number before relying on this account during pickup execution." },
    shipper.email
      ? { key: "email-ready", label: "Email lane ready", tone: "READY" as const, body: "This shipper record is ready for digital paperwork and onboarding follow-up." }
      : { key: "email-missing", label: "Email lane missing", tone: "ACTION" as const, body: "Add a primary shipper email so paperwork, setup follow-up, and invoice communication have a durable lane." },
  ];

  const shipperOnboardingPrompts = [
    shipper.shippingNotes
      ? { key: "shipping-ready", label: "Shipping instructions documented", tone: "READY" as const, body: "Operational shipping notes are already captured for this shipper." }
      : { key: "shipping-missing", label: "Shipping instructions missing", tone: "ACTION" as const, body: "Document dock requirements, timing expectations, or handling rules before live loads begin moving." },
    shipper.billingNotes
      ? { key: "billing-ready", label: "Billing notes documented", tone: "READY" as const, body: "Billing expectations are already captured for this shipper." }
      : { key: "billing-watch", label: "Billing notes still open", tone: "WATCH" as const, body: "Capture invoice routing and payment handling expectations before the billing loop starts." },
    shipper.nextFollowUpAt
      ? { key: "followup-ready", label: "Next follow-up scheduled", tone: "READY" as const, body: "A next follow-up date is already set for this shipper account." }
      : { key: "followup-missing", label: "Next follow-up missing", tone: "ACTION" as const, body: "Set the next follow-up date so the account does not stall between setup and first-load execution." },
  ];

  return (
    <div className="space-y-6">
      <PageHeader title={shipper.companyName} subtitle="Shipper record, contact details, shipping notes, and billing notes." />

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

      <CrmReturnHeader
        listHref={listHref}
        listLabel="shippers"
        editHref={appendReturnTo(`/shippers/${shipper.id}/edit`, currentReturnTo)}
        editLabel="Edit Shipper"
        stage={shipper.crmStage}
        isActive={shipper.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">Shipper 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="/shippers"
        listHref={listHref}
        listLabel="shippers"
        createHref={intelligenceCreateHref}
        createLabel="Create Shipper"
        title="Shipper profile"
        subtitle="Contact lanes, shipping guidance, billing context, and follow-up timing are now surfaced before the rest of the account detail workflow."
        continuityLabel={shipper.shippingNotes && shipper.billingAddress ? "Operational guidance present" : shipper.phone && shipper.email ? "Contact lanes ready" : "Needs profile cleanup"}
        continuityTone={shipper.shippingNotes && shipper.billingAddress ? "good" : shipper.phone && shipper.email ? "watch" : "action"}
        facts={[
          { label: "Primary contact", value: shipper.contactName || shipper.email || "-" },
          { label: "Billing address", value: shipper.billingAddress || "-" },
          { label: "Last contacted", value: dateValue(shipper.lastContactedAt) },
          { label: "Next follow-up", value: dateValue(shipper.nextFollowUpAt) },
        ]}
        sectionLinks={[
          { href: "#shipper-profile", label: "Profile" },
          { href: "#operational-notes", label: "Operational notes" },
          { href: "#lifecycle-controls", label: "Follow-up" },
          { href: "#crm-timeline", label: "Timeline" },
        ]}
      />
        </div>
      </details>


      <CrmDetailActionBar
        primaryActions={[
          { href: listHref, label: "Back to Shippers" },
          { href: appendReturnTo(`/shippers/${shipper.id}/edit`, currentReturnTo), label: "Edit Shipper", tone: "primary" },
          ...(shipper.phone ? [{ href: `/cori/quotes`, label: "Call Shipper", popupContext: { source: "shippers", contactType: "shipper", contactName: shipper.contactName || shipper.companyName, phone: shipper.phone || undefined, companyLabel: shipper.companyName, purpose: "ETA_UPDATE" } }] : []),
          ...(shipper.phone ? [{ href: `/cori/quotes?source=shippers&contactType=shipper&contactName=${encodeURIComponent(shipper.contactName || shipper.companyName)}&phone=${encodeURIComponent(shipper.phone || "")}&companyLabel=${encodeURIComponent(shipper.companyName)}&purpose=ETA_UPDATE&returnTo=${encodeURIComponent(currentReturnTo)}`, label: "Call" }] : []),
          ...(shipper.email ? [{ href: `mailto:${shipper.email}`, label: "Email Shipper" }] : []),
        ]}
        jumpActions={[
          { href: "#lifecycle-controls", label: "Follow-up controls" },
          { href: "#crm-timeline", label: "Activity history" },
          { href: "#operational-notes", label: "Operational Notes" },
        ]}
        stateAction={{
          label: working ? "Working..." : shipper.isActive === false ? "Reactivate Shipper" : "Deactivate Shipper",
          tone: shipper.isActive === false ? "default" : "danger",
          disabled: working,
          onClick: toggleActive,
        }}
      />

      <CrmSummaryStrip
        items={[
          { label: "Primary contact", value: shipper.contactName || shipper.email || "-" },
          { label: "Last contacted", value: dateValue(shipper.lastContactedAt) },
          { label: "Next follow-up", value: dateValue(shipper.nextFollowUpAt) },
          { label: "Revenue In", value: money(shipper.revenueIn) },
        ]}
      />


      <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">
      {(shipper.phone) ? (
        <QuoteCallContinuity
          phone={shipper.phone}
          contactName={shipper.contactName || shipper.companyName}
          launchHref={`/cori/quotes?source=shippers&contactName=${encodeURIComponent(shipper.contactName || shipper.companyName)}&phone=${encodeURIComponent(shipper.phone || "")}&returnTo=${encodeURIComponent(currentReturnTo)}`}
        />
      ) : null}
      <CallNoteContinuity
        entityType="shipper"
        entityId={shipper.id}
        entityName={shipper.companyName}
        contactName={shipper.contactName || shipper.companyName}
        phoneNumber={shipper.phone}
      />
        </div>
      </details>

      <div id="shipper-profile" className="grid gap-6 xl:grid-cols-2">
        <Card title="Shipper summary">
          <Row label="Company name" value={shipper.companyName} />
          <Row label="Primary contact" value={shipper.contactName} />
          <Row label="Status" value={shipper.isActive === false ? "Inactive" : "Active"} />
        </Card>
        <Card title="Commercial and contact">
          <Row label="Phone" value={shipper.phone} />
          <Row label="Email" value={shipper.email ? <a href={`mailto:${shipper.email}`} className="hover:underline">{shipper.email}</a> : "-"} />
          <Row label="Website" value={shipper.website ? <a href={shipper.website} target="_blank" rel="noreferrer" className="hover:underline">{shipper.website}</a> : "-"} />
          <Row label="Revenue In" value={money(shipper.revenueIn)} />
          <Row label="Payments Out" value={money(shipper.paymentsOut)} />
          <Row label="Last contacted" value={dateValue(shipper.lastContactedAt)} />
          <Row label="Next follow-up" value={dateValue(shipper.nextFollowUpAt)} />
        </Card>
      </div>
      <div id="operational-notes" className="scroll-mt-24"><Card title="Operational notes">
          <Row label="Billing address" value={shipper.billingAddress} />
          <Row label="Shipping notes" value={shipper.shippingNotes} />
          <Row label="Billing notes" value={shipper.billingNotes} />
          <Row label="General notes" value={shipper.notesText} />
        </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">Shipper 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="shipper account"
        editHref={appendReturnTo(`/shippers/${shipper.id}/edit`, currentReturnTo)}
        checklist={onboardingChecklist}
        contactPrompts={shipperContactPrompts}
        onboardingPrompts={shipperOnboardingPrompts}
      />

      <AssignmentPanel targetType="SHIPPER" targetId={shipper.id} targetLabel="shipper" />

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