"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 { Company } 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 CompanyDetailPage() {
  const params = useParams<{ id: string }>();
  const [company, setCompany] = useState<Company | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [working, setWorking] = useState(false);
  const { currentReturnTo, listHref } = useCrmReturnTo("/companies");
  const intelligenceParams = useMemo(() => getIntelligenceParamsFromHref(listHref), [listHref]);
  const intelligenceCreateHref = useMemo(() => {
    if (!intelligenceParams) return `/companies/new`;
    return buildIntelligenceCreateHref({
      source: "intelligence",
      entityType: "company",
      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<{ company: Company }>(`/api/companies/${params.id}`)
      .then((data) => setCompany(data.company))
      .catch((e) => setError(e?.message ?? "Failed to load company"));
  }, [params?.id]);

  async function reloadRecord() {
    if (!params?.id) return;
    const data = await apiGet<{ company: Company }>(`/api/companies/${params.id}`);
    setCompany(data.company);
  }

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

  const onboardingChecklist = [
    { key: "legal-name", label: "Legal name", complete: Boolean(company.legalName), helpText: "A legal business name is needed before using this record as a real customer or carrier account." },
    { key: "contact-name", label: "Primary contact", complete: Boolean(company.contactName), helpText: "A named primary contact keeps onboarding ownership clear." },
    { key: "phone", label: "Direct phone", complete: Boolean(company.phone), helpText: "Dispatch and billing teams need a direct phone path for escalations and day-of-load coordination." },
    { key: "email", label: "Primary email", complete: Boolean(company.email), helpText: "Email is needed for contracts, billing, setup paperwork, and dispatch follow-up." },
    { key: "authority", label: "MC or DOT number", complete: Boolean(company.mcNumber || company.dotNumber), helpText: "Authority identifiers help validate the company before operational use." },
    { key: "billing-address", label: "Billing address", complete: Boolean(company.billingAddress), helpText: "Billing and invoice routing are incomplete until a billing address is captured." },
  ];

  const companyContactPrompts = [
    company.contactName
      ? { key: "contact-ready", label: "Named contact ready", tone: "READY" as const, body: `Primary contact is ${company.contactName}, which gives the team a clear onboarding owner.` }
      : { key: "contact-missing", label: "Named contact missing", tone: "ACTION" as const, body: "Add a named company contact before using this record for active client or partner onboarding." },
    company.phone
      ? { key: "phone-ready", label: "Phone ready", tone: "READY" as const, body: "Dispatch and account teams can call this company directly." }
      : { key: "phone-missing", label: "Direct call lane missing", tone: "ACTION" as const, body: "Capture a direct company phone number before relying on this record during live operating work." },
    company.email
      ? { key: "email-ready", label: "Email lane ready", tone: "READY" as const, body: "This company record is ready for digital paperwork, billing communication, and setup follow-up." }
      : { key: "email-missing", label: "Email lane missing", tone: "ACTION" as const, body: "Add a primary company email before treating this record as onboarding-complete." },
  ];

  const companyOnboardingPrompts = [
    company.ownerOperators?.length
      ? { key: "linked-ready", label: "Linked operator present", tone: "READY" as const, body: "This company already has linked owner operators." }
      : { key: "linked-watch", label: "No linked operator footprint yet", tone: "WATCH" as const, body: "If this company will be used operationally, link the relevant owner operators or carriers early." },
    company.notesText
      ? { key: "notes-ready", label: "Internal notes documented", tone: "READY" as const, body: "Internal onboarding context has been captured for this company." }
      : { key: "notes-watch", label: "Internal notes still thin", tone: "WATCH" as const, body: "Add setup notes, handling expectations, or account context so the team can work the record consistently." },
    company.nextFollowUpAt
      ? { key: "followup-ready", label: "Follow-up cadence scheduled", tone: "READY" as const, body: "A next follow-up date is already set for this company record." }
      : { key: "followup-missing", label: "Follow-up cadence missing", tone: "ACTION" as const, body: "Set the next follow-up date so onboarding momentum is not lost after initial setup." },
  ];

  return (
    <div className="space-y-6">
      <PageHeader title={company.name} subtitle="Company record, contact details, and linked owner operators." />

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

      <CrmReturnHeader
        listHref={listHref}
        listLabel="companies"
        editHref={appendReturnTo(`/companies/${company.id}/edit`, currentReturnTo)}
        editLabel="Edit Company"
        stage={company.crmStage}
        isActive={company.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">Company 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="/companies"
        listHref={listHref}
        listLabel="companies"
        createHref={intelligenceCreateHref}
        createLabel="Create Company"
        title="Company profile"
        subtitle="Commercial identity, authority details, and linked owner-operator context now stay visible in one consistent top section."
        continuityLabel={company.ownerOperators?.length ? "Linked partner context present" : company.mcNumber || company.dotNumber ? "Authority captured" : "Needs profile cleanup"}
        continuityTone={company.ownerOperators?.length ? "good" : company.mcNumber || company.dotNumber ? "watch" : "action"}
        facts={[
          { label: "Primary contact", value: company.contactName || company.email || "-" },
          { label: "Last contacted", value: dateValue(company.lastContactedAt) },
          { label: "Next follow-up", value: dateValue(company.nextFollowUpAt) },
          { label: "Owner operators", value: company.ownerOperators?.length ?? 0 },
        ]}
        sectionLinks={[
          { href: "#company-profile", label: "Profile" },
          { href: "#owner-operators", label: "Owner ops" },
          { href: "#lifecycle-controls", label: "Follow-up" },
          { href: "#crm-timeline", label: "Timeline" },
        ]}
      />
        </div>
      </details>


      <CrmDetailActionBar
        primaryActions={[
          { href: listHref, label: "Back to Companies" },
          { href: appendReturnTo(`/companies/${company.id}/edit`, currentReturnTo), label: "Edit Company", tone: "primary" },
          ...(company.phone ? [{ href: `tel:${company.phone}`, label: "Call Company" }] : []),
          ...(company.phone ? [{ href: `/cori/quotes?source=companies&contactName=${encodeURIComponent(company.contactName || company.name)}&phone=${encodeURIComponent(company.phone || "")}&returnTo=${encodeURIComponent(currentReturnTo)}`, label: "Quote Call" }] : []),
          ...(company.email ? [{ href: `mailto:${company.email}`, label: "Email Company" }] : []),
        ]}
        relationshipActions={[
          ...(company.ownerOperators?.length ? [{ href: "#linked-owner-operators", label: `Owner Operators (${company.ownerOperators.length})` }] : []),
        ]}
        jumpActions={[
          { href: "#lifecycle-controls", label: "Follow-up controls" },
          { href: "#crm-timeline", label: "Activity history" },
          { href: "#linked-owner-operators", label: "Linked Owner Operators" },
        ]}
        stateAction={{
          label: working ? "Working..." : company.isActive === false ? "Reactivate Company" : "Deactivate Company",
          tone: company.isActive === false ? "default" : "danger",
          disabled: working,
          onClick: toggleActive,
        }}
      />

      <CrmSummaryStrip
        items={[
          { label: "Primary contact", value: company.contactName || company.email || "-" },
          { label: "Last contacted", value: dateValue(company.lastContactedAt) },
          { label: "Next follow-up", value: dateValue(company.nextFollowUpAt) },
          { label: "Linked owner operators", value: company.ownerOperators?.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">
      {(company.phone) ? (
        <QuoteCallContinuity
          phone={company.phone}
          contactName={company.contactName || company.name}
          launchHref={`/cori/quotes?source=companies&contactName=${encodeURIComponent(company.contactName || company.name)}&phone=${encodeURIComponent(company.phone || "")}&returnTo=${encodeURIComponent(currentReturnTo)}`}
        />
      ) : null}
      <CallNoteContinuity
        entityType="company"
        entityId={company.id}
        entityName={company.name}
        contactName={company.contactName || company.name}
        phoneNumber={company.phone}
      />
        </div>
      </details>

      <div id="company-profile" className="grid gap-6 xl:grid-cols-2">
        <Card title="Company summary">
          <Row label="Company name" value={company.name} />
          <Row label="Legal name" value={company.legalName} />
          <Row label="MC number" value={company.mcNumber} />
          <Row label="DOT number" value={company.dotNumber} />
          <Row label="Status" value={company.isActive === false ? "Inactive" : "Active"} />
        </Card>
        <Card title="Commercial and contact">
          <Row label="Primary contact" value={company.contactName} />
          <Row label="Phone" value={company.phone} />
          <Row label="Email" value={company.email ? <a href={`mailto:${company.email}`} className="hover:underline">{company.email}</a> : "-"} />
          <Row label="Website" value={company.website ? <a href={company.website} target="_blank" rel="noreferrer" className="hover:underline">{company.website}</a> : "-"} />
          <Row label="Revenue In" value={money(company.revenueIn)} />
          <Row label="Payments Out" value={money(company.paymentsOut)} />
          <Row label="Last contacted" value={dateValue(company.lastContactedAt)} />
          <Row label="Next follow-up" value={dateValue(company.nextFollowUpAt)} />
        </Card>
      </div>
      <div id="owner-operators" className="scroll-mt-24"><Card title="Notes and linked owner operators">
        <Row label="Billing address" value={company.billingAddress} />
        <Row label="Notes" value={company.notesText} />
        <div id="linked-owner-operators" className="scroll-mt-24 pt-4">
          <div className="mb-3 text-sm font-medium text-gray-500">Linked owner operators</div>
          {company.ownerOperators?.length ? (
            <div className="space-y-2">
              {company.ownerOperators.map((item) => (
                <div key={item.id} className="rounded-xl border px-4 py-3 text-sm">
                  <div className="font-medium"><Link href={appendReturnTo(`/owner-operators/${item.id}`, currentReturnTo)} className="hover:underline">{item.businessName}</Link></div>
                  <div className="mt-1 text-gray-500">{item.crmStage ?? "-"} • Revenue In {money(item.revenueIn)} • Payments Out {money(item.paymentsOut)}</div>
                </div>
              ))}
            </div>
          ) : <div className="text-sm text-gray-500">No owner operators linked yet.</div>}
        </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">Company 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="company account"
        editHref={appendReturnTo(`/companies/${company.id}/edit`, currentReturnTo)}
        checklist={onboardingChecklist}
        contactPrompts={companyContactPrompts}
        onboardingPrompts={companyOnboardingPrompts}
      />

      <AssignmentPanel targetType="COMPANY" targetId={company.id} targetLabel="company" />

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