"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { apiGet, apiPost } from "@/lib/api";
import type { OwnerOperator } 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 { DocumentPaperworkPanel } from "@/components/crm/paperwork-check-panel";
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 OwnerOperatorDetailPage() {
  const params = useParams<{ id: string }>();
  const [record, setRecord] = useState<OwnerOperator | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [working, setWorking] = useState(false);
  const { currentReturnTo, listHref } = useCrmReturnTo("/owner-operators");

  useEffect(() => {
    if (!params?.id) return;
    apiGet<{ ownerOperator: OwnerOperator }>(`/api/owner-operators/${params.id}`)
      .then((data) => setRecord(data.ownerOperator))
      .catch((e) => setError(e?.message ?? "Failed to load owner operator"));
  }, [params?.id]);

  async function reloadRecord() {
    if (!params?.id) return;
    const data = await apiGet<{ ownerOperator: OwnerOperator }>(`/api/owner-operators/${params.id}`);
    setRecord(data.ownerOperator);
  }

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

  const contactName = [record.firstName, record.lastName].filter(Boolean).join(" ");
  const linkedDriverName = [record.driver?.firstName, record.driver?.lastName].filter(Boolean).join(" ") || record.driver?.email || "Driver";

  const documentChecklist = [
    { key: "mc-number", label: "MC number on file", complete: Boolean(record.mcNumber), helpText: "The operating authority reference should be captured before treating the owner operator as dispatch-ready." },
    { key: "dot-number", label: "DOT number on file", complete: Boolean(record.dotNumber), helpText: "DOT identity supports carrier verification, broker confidence, and compliance follow-up." },
    { key: "phone", label: "Direct phone", complete: Boolean(record.phone), helpText: "A direct phone number keeps dispatch, after-hours, and exception handling from depending on indirect contacts." },
    { key: "email", label: "Direct email", complete: Boolean(record.email), helpText: "A direct email simplifies paperwork, billing coordination, and account recovery workflows." },
    { key: "linked-driver", label: "Linked driver", complete: Boolean(record.driver), helpText: "A linked driver makes this record easier to use in dispatch." },
    { key: "linked-truck", label: "Linked truck", complete: Boolean(record.truck), helpText: "A linked truck helps dispatch move faster when the owner operator becomes active on loads." },
  ];

  const compliancePrompts = [
    record.mcNumber && record.dotNumber
      ? { key: "authority-ready", label: "Authority identifiers present", tone: "READY" as const, body: "MC and DOT numbers are both saved." }
      : { key: "authority-missing", label: "Authority follow-up needed", tone: "ACTION" as const, body: "Capture both MC and DOT references before treating this owner operator as fully dispatch-ready." },
    record.phone
      ? { key: "contact-ready", label: "Dispatch contact path ready", tone: "READY" as const, body: "A direct phone number is present for load updates, pickup coordination, and exception handling." }
      : { key: "contact-missing", label: "Direct dispatch contact missing", tone: "ACTION" as const, body: "Add a direct phone number so this owner operator can be reached without manual relays." },
    record.email
      ? { key: "email-ready", label: "Paperwork delivery path", tone: "READY" as const, body: "A direct email is available for onboarding packets, billing notes, and auth recovery workflows." }
      : { key: "email-watch", label: "Email missing", tone: "WATCH" as const, body: "No direct email is present. The record may still operate, but paperwork follow-up may require slower manual coordination." },
  ];

  const handoffItems = [
    record.company
      ? { key: "company-handoff", label: "Company linked", tone: "READY" as const, body: `This owner operator is linked to ${record.company.name}.` }
      : { key: "company-handoff-missing", label: "Company context missing", tone: "WATCH" as const, body: "No parent company is linked. Confirm whether this owner operator should operate independently or under a company relationship." },
    record.driver
      ? { key: "driver-handoff", label: "Driver linked", tone: "READY" as const, body: `The linked driver is ${linkedDriverName}.` }
      : { key: "driver-handoff-missing", label: "Driver missing", tone: "ACTION" as const, body: "Link a driver before using this owner operator for active dispatch work." },
    record.truck
      ? { key: "truck-handoff", label: "Truck linked", tone: "READY" as const, body: `Truck ${record.truck.truckNumber} is already linked.` }
      : { key: "truck-handoff-missing", label: "Truck missing", tone: "WATCH" as const, body: "No truck is linked yet. Confirm equipment assignment before using this record for active work." },
  ];

  return (
    <div className="space-y-6">
      <PageHeader title={record.businessName} subtitle="Owner operator record, linked truck, linked driver, and follow-up details." />

      <CrmReturnHeader
        listHref={listHref}
        listLabel="owner operators"
        editHref={appendReturnTo(`/owner-operators/${record.id}/edit`, currentReturnTo)}
        editLabel="Edit Owner Operator"
        stage={record.crmStage}
        isActive={record.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">Owner operator 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="/owner-operators"
        listHref={listHref}
        listLabel="owner operators"
        createHref="/owner-operators/new"
        createLabel="Create Owner Operator"
        title="Owner-operator profile"
        subtitle="Authority details, linked company, driver, and truck are summarized first."
        continuityLabel={record.driver && record.truck ? "Driver and truck linked" : record.mcNumber && record.dotNumber ? "Authority captured" : "Needs profile cleanup"}
        continuityTone={record.driver && record.truck ? "good" : record.mcNumber && record.dotNumber ? "watch" : "action"}
        facts={[
          { label: "Primary contact", value: contactName || record.email || "-" },
          { label: "Linked company", value: record.company ? <Link href={appendReturnTo(`/companies/${record.company.id}`, currentReturnTo)} className="hover:underline">{record.company.name}</Link> : "-" },
          { label: "Linked truck", value: record.truck ? <Link href={`/trucks/${record.truck.id}`} className="hover:underline">{record.truck.truckNumber}</Link> : "-" },
          { label: "Next follow-up", value: dateValue(record.nextFollowUpAt) },
        ]}
        sectionLinks={[
          { href: "#owner-operator-profile", label: "Profile" },
          { href: "#paperwork-check", label: "Paperwork" },
          { href: "#notes-section", label: "Notes" },
          { href: "#lifecycle-controls", label: "Follow-up" },
          { href: "#crm-timeline", label: "Timeline" },
        ]}
      />
        </div>
      </details>


      <CrmDetailActionBar
        primaryActions={[
          { href: listHref, label: "Back to Owner Operators" },
          { href: appendReturnTo(`/owner-operators/${record.id}/edit`, currentReturnTo), label: "Edit Owner Operator", tone: "primary" },
          ...(record.phone ? [{ href: `tel:${record.phone}`, label: "Call Owner Operator" }] : []),
          ...(record.phone ? [{ href: `/cori/quotes?source=owner-operators&contactName=${encodeURIComponent(record.businessName || [record.firstName, record.lastName].filter(Boolean).join(" ") || "Owner Operator")}&phone=${encodeURIComponent(record.phone || "")}&returnTo=${encodeURIComponent(currentReturnTo)}`, label: "Quote Call" }] : []),
          ...(record.email ? [{ href: `mailto:${record.email}`, label: "Email Owner Operator" }] : []),
        ]}
        relationshipActions={[
          ...(record.company ? [{ href: appendReturnTo(`/companies/${record.company.id}`, currentReturnTo), label: record.company.name }] : []),
          ...(record.driver ? [{ href: appendReturnTo(`/drivers/${record.driver.id}`, currentReturnTo), label: linkedDriverName }] : []),
          ...(record.truck ? [{ href: `/trucks/${record.truck.id}`, label: `Truck ${record.truck.truckNumber}` }] : []),
        ]}
        jumpActions={[
          { href: "#paperwork-check", label: "Paperwork check" },
          { href: "#lifecycle-controls", label: "Follow-up controls" },
          { href: "#crm-timeline", label: "Activity history" },
          { href: "#notes-section", label: "Notes" },
        ]}
        stateAction={{
          label: working ? "Working..." : record.isActive === false ? "Reactivate Owner Operator" : "Deactivate Owner Operator",
          tone: record.isActive === false ? "default" : "danger",
          disabled: working,
          onClick: toggleActive,
        }}
      />

      <CrmSummaryStrip
        items={[
          { label: "Primary contact", value: contactName || record.email || "-" },
          { label: "Linked company", value: record.company ? <Link href={appendReturnTo(`/companies/${record.company.id}`, currentReturnTo)} className="hover:underline">{record.company.name}</Link> : "-" },
          { label: "Linked truck", value: record.truck ? <Link href={`/trucks/${record.truck.id}`} className="hover:underline">{record.truck.truckNumber}</Link> : "-" },
          { label: "Next follow-up", value: dateValue(record.nextFollowUpAt) },
        ]}
      />


      <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">
      {(record.phone) ? (
        <QuoteCallContinuity
          phone={record.phone}
          contactName={record.businessName || [record.firstName, record.lastName].filter(Boolean).join(" ") || "Owner Operator"}
          launchHref={`/cori/quotes?source=owner-operators&contactName=${encodeURIComponent(record.businessName || [record.firstName, record.lastName].filter(Boolean).join(" ") || "Owner Operator")}&phone=${encodeURIComponent(record.phone || "")}&returnTo=${encodeURIComponent(currentReturnTo)}`}
        />
      ) : null}
      <CallNoteContinuity
        entityType="ownerOperator"
        entityId={record.id}
        entityName={record.businessName || contactName || "Owner Operator"}
        contactName={record.businessName || [record.firstName, record.lastName].filter(Boolean).join(" ") || "Owner Operator"}
        phoneNumber={record.phone}
      />
        </div>
      </details>

      <div id="owner-operator-profile" className="grid gap-6 xl:grid-cols-2">
        <Card title="Identity and lifecycle">
          <Row label="Business name" value={record.businessName} />
          <Row label="Contact name" value={contactName} />
          <Row label="MC number" value={record.mcNumber} />
          <Row label="DOT number" value={record.dotNumber} />
          <Row label="Status" value={record.isActive === false ? "Inactive" : "Active"} />
        </Card>
        <Card title="Commercial and linked operations">
          <Row label="Phone" value={record.phone} />
          <Row label="Email" value={record.email ? <a href={`mailto:${record.email}`} className="hover:underline">{record.email}</a> : "-"} />
          <Row label="Revenue In" value={money(record.revenueIn)} />
          <Row label="Payments Out" value={money(record.paymentsOut)} />
          <Row label="Last contacted" value={dateValue(record.lastContactedAt)} />
          <Row label="Next follow-up" value={dateValue(record.nextFollowUpAt)} />
          <Row label="Linked company" value={record.company ? <Link href={appendReturnTo(`/companies/${record.company.id}`, currentReturnTo)} className="hover:underline">{record.company.name}</Link> : "-"} />
          <Row label="Linked driver" value={record.driver ? <Link href={appendReturnTo(`/drivers/${record.driver.id}`, currentReturnTo)} className="hover:underline">{linkedDriverName}</Link> : "-"} />
          <Row label="Linked truck" value={record.truck ? <Link href={`/trucks/${record.truck.id}`} className="hover:underline">{record.truck.truckNumber}</Link> : "-"} />
        </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">Owner operator setup checks</div>
            <div className="mt-1 text-xs text-slate-500">Open only when checking documents, ownership, 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">
      <div id="paperwork-check" className="scroll-mt-24">
        <DocumentPaperworkPanel
          entityLabel="owner operator record"
          editHref={appendReturnTo(`/owner-operators/${record.id}/edit`, currentReturnTo)}
          checklist={documentChecklist}
          compliancePrompts={compliancePrompts}
          handoffItems={handoffItems}
        />
      </div>

      <div id="notes-section" className="scroll-mt-24">
        <Card title="Notes"><Row label="General notes" value={record.notesText} /></Card>
      </div>
      <AssignmentPanel targetType="OWNER_OPERATOR" targetId={record.id} targetLabel="owner operator" />

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