"use client";

import { useEffect, useMemo, useState } from "react";
import { apiGet, apiPost } from "@/lib/api";
import type { Load, Driver, Truck, LoadDocumentRecord } from "@/types";

type VisibilityScope = "INTERNAL_ONLY" | "FIELD_VISIBLE" | "ACCOUNTING_ONLY" | "CUSTOMER_VISIBLE";
type Category = "RATE_CONFIRMATION" | "POD" | "BOL" | "RECEIPT" | "SCALE_TICKET" | "LUMPER_RECEIPT" | "FUEL_RECEIPT" | "GENERAL_ATTACHMENT" | "OTHER";
type Tone = "good" | "watch" | "alert" | "default";

type DocumentFormValues = {
  fileName: string;
  category: Category;
  visibilityScope: VisibilityScope;
  fieldLabel: string;
  isFieldRequired: boolean;
};

const emptyForm: DocumentFormValues = {
  fileName: "",
  category: "RATE_CONFIRMATION",
  visibilityScope: "INTERNAL_ONLY",
  fieldLabel: "",
  isFieldRequired: false,
};

function toneClasses(tone: Tone) {
  if (tone === "good") return "border-emerald-200 bg-emerald-50 text-emerald-700";
  if (tone === "watch") return "border-amber-200 bg-amber-50 text-amber-700";
  if (tone === "alert") return "border-red-200 bg-red-50 text-red-700";
  return "border-slate-200 bg-slate-50 text-slate-700";
}

function formatDate(value?: string | null) {
  if (!value) return "-";
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? value : d.toLocaleString();
}

function visibilityLabel(scope: VisibilityScope) {
  return {
    INTERNAL_ONLY: "Office only",
    FIELD_VISIBLE: "Field visible",
    ACCOUNTING_ONLY: "Accounting only",
    CUSTOMER_VISIBLE: "Customer visible",
  }[scope];
}

function categoryLabel(category: Category | string) {
  return category.replaceAll("_", " ");
}


type DocumentCategoryRequirement = {
  label: string;
  detail: string;
  complete: boolean;
  tone: Tone;
};

function getDocumentCategoryEnforcementState(load: Load, documents: LoadDocumentRecord[]) {
  const categories = new Set(documents.map((doc) => doc.category));
  const hasRateCon = categories.has("RATE_CONFIRMATION") || Boolean(load.rateConfirmationNumber);
  const hasBol = categories.has("BOL");
  const hasPod = categories.has("POD");
  const hasInvoiceAnchor = Boolean(load.payments?.length || load.invoiceAmount || load.financialSummary?.grossRevenue);
  const hasPaymentReference = Boolean(load.payments?.some((payment) => payment.paymentReference));
  const activeOrLater = ["AVAILABLE", "ASSIGNED", "IN_TRANSIT", "DELIVERED", "INVOICED", "PAID_FULL"].includes(load.status);
  const inTransitOrLater = ["IN_TRANSIT", "DELIVERED", "INVOICED", "PAID_FULL"].includes(load.status);
  const deliveredOrLater = ["DELIVERED", "INVOICED", "PAID_FULL"].includes(load.status);
  const paidFull = load.status === "PAID_FULL";

  const requirements: DocumentCategoryRequirement[] = [
    {
      label: "Rate confirmation",
      detail: hasRateCon ? "Broker intake anchor is visible" : "Active loads should carry a rate confirmation anchor",
      complete: !activeOrLater || hasRateCon,
      tone: !activeOrLater ? "default" : hasRateCon ? "good" : "alert",
    },
    {
      label: "BOL / movement anchor",
      detail: hasBol ? "BOL intake entry is visible" : "In-transit or later loads benefit from a BOL anchor",
      complete: !inTransitOrLater || hasBol,
      tone: !inTransitOrLater ? "default" : hasBol ? "good" : "watch",
    },
    {
      label: "POD / delivery proof",
      detail: hasPod ? "POD intake entry is visible" : "Delivered or later loads should carry POD visibility",
      complete: !deliveredOrLater || hasPod,
      tone: !deliveredOrLater ? "default" : hasPod ? "good" : "alert",
    },
    {
      label: "Invoice anchor",
      detail: hasInvoiceAnchor ? "Invoice amount or payment record is visible" : "Delivered or later loads should show an invoice anchor",
      complete: !deliveredOrLater || hasInvoiceAnchor,
      tone: !deliveredOrLater ? "default" : hasInvoiceAnchor ? "good" : "alert",
    },
    {
      label: "Payment reference",
      detail: hasPaymentReference ? "Payment reference is visible for closeout" : "Paid loads should carry a payment reference for clean closeout",
      complete: !paidFull || hasPaymentReference,
      tone: !paidFull ? "default" : hasPaymentReference ? "good" : "watch",
    },
  ];

  const prompts = [
    activeOrLater && !hasRateCon ? "Add or confirm a RATE_CONFIRMATION document anchor before the load drifts further into execution." : null,
    inTransitOrLater && !hasBol ? "Add a BOL category document so movement-stage paperwork is visible to the office and field path." : null,
    deliveredOrLater && !hasPod ? "Add a POD before treating delivery paperwork as complete." : null,
    deliveredOrLater && !hasInvoiceAnchor ? "Create or confirm the invoice anchor so the billing package is operationally complete." : null,
    paidFull && !hasPaymentReference ? "Record a payment reference so the final closeout package is audit-friendly." : null,
  ].filter(Boolean) as string[];

  const missingCore = requirements.filter((item) => item.tone === "alert").length;
  const tone: Tone = missingCore === 0 && prompts.length === 0 ? "good" : missingCore <= 1 ? "watch" : "alert";
  const nextAction =
    activeOrLater && !hasRateCon ? "Add the rate confirmation category" :
    inTransitOrLater && !hasBol ? "Add the BOL category" :
    deliveredOrLater && !hasPod ? "Add the POD category" :
    deliveredOrLater && !hasInvoiceAnchor ? "Confirm the invoice package anchor" :
    paidFull && !hasPaymentReference ? "Capture the payment reference" :
    "Document categories are aligned with the current lifecycle stage";

  const packageChecks = [
    { label: "Operational package", value: `${hasRateCon ? "Rate con" : "No rate con"} • ${hasBol ? "BOL" : "No BOL"}`, tone: hasRateCon ? "good" : "watch" as Tone },
    { label: "Delivery package", value: `${hasPod ? "POD" : "No POD"} • ${hasInvoiceAnchor ? "Invoice anchor" : "No invoice anchor"}`, tone: deliveredOrLater && (!hasPod || !hasInvoiceAnchor) ? "alert" : deliveredOrLater ? "good" : "default" as Tone },
    { label: "Closeout package", value: `${hasPaymentReference ? "Payment ref" : "No payment ref"}`, tone: paidFull && !hasPaymentReference ? "watch" : paidFull ? "good" : "default" as Tone },
  ];

  return { requirements, prompts, tone, nextAction, packageChecks };
}

function getAccessHardeningState(load: Load, documents: LoadDocumentRecord[], driver?: Driver | null, truck?: Truck | null) {
  const internalOnly = documents.filter((doc) => doc.visibilityScope === "INTERNAL_ONLY").length;
  const fieldVisible = documents.filter((doc) => doc.visibilityScope === "FIELD_VISIBLE").length;
  const accountingOnly = documents.filter((doc) => doc.visibilityScope === "ACCOUNTING_ONLY").length;
  const customerVisible = documents.filter((doc) => doc.visibilityScope === "CUSTOMER_VISIBLE").length;

  const hasRateCon = documents.some((doc) => doc.category === "RATE_CONFIRMATION") || Boolean(load.rateConfirmationNumber);
  const hasPod = documents.some((doc) => doc.category === "POD");
  const hasBol = documents.some((doc) => doc.category === "BOL");
  const hasFieldContext = Boolean(driver?.id || truck?.id || load.driver?.id || load.truck?.id);
  const deliveredOrLater = ["DELIVERED", "INVOICED", "PAID_FULL"].includes(load.status);

  const prompts = [
    !load.id || load.id === "draft-load-preview" ? "Save the load first so document intake entries can be attached to a real lifecycle record." : null,
    !hasRateCon && ["AVAILABLE", "ASSIGNED", "IN_TRANSIT", "DELIVERED", "INVOICED", "PAID_FULL"].includes(load.status) ? "Create a rate confirmation document intake entry so office users can see the anchor directly on the load." : null,
    !hasFieldContext && fieldVisible > 0 ? "Field-visible documents exist without a clear assigned driver or truck context. Confirm the assignment path before relying on field access." : null,
    deliveredOrLater && !hasPod ? "Delivered or later loads should carry a POD intake entry before the billing and closeout loop is treated as documentary complete." : null,
    load.status === "IN_TRANSIT" && !hasBol ? "In-transit loads benefit from a BOL intake entry so field and office users are looking at the same movement anchor." : null,
    accountingOnly > 0 && internalOnly === 0 ? "Accounting-only entries are present without a general office-visible companion. Add an office-facing intake note if dispatch also needs the document anchor." : null,
  ].filter(Boolean) as string[];

  const tone: Tone = prompts.length === 0 ? "good" : prompts.length <= 2 ? "watch" : "alert";
  const label = prompts.length === 0 ? "Document access looks good" : prompts.length <= 2 ? "Check document access" : "Document access needs review";

  const splitHighlights: Array<{ label: string; value: string; tone: Tone }> = [
    {
      label: "Field / office split",
      value: `${fieldVisible} field-visible • ${internalOnly} office-only`,
      tone: fieldVisible > 0 || internalOnly > 0 ? "good" : "watch",
    },
    {
      label: "Restricted visibility",
      value: `${accountingOnly} accounting-only • ${customerVisible} customer-visible`,
      tone: accountingOnly > 0 || customerVisible > 0 ? "default" : "default",
    },
    {
      label: "Lifecycle coverage",
      value: `${hasRateCon ? "Rate con" : "No rate con"} • ${hasBol ? "BOL" : "No BOL"} • ${hasPod ? "POD" : "No POD"}`,
      tone: deliveredOrLater && !hasPod ? "alert" : hasRateCon ? "good" : "watch",
    },
  ];

  const nextAction =
    !load.id || load.id === "draft-load-preview" ? "Save the load to unlock document intake" :
    !hasRateCon && ["AVAILABLE", "ASSIGNED", "IN_TRANSIT", "DELIVERED", "INVOICED", "PAID_FULL"].includes(load.status) ? "Add a rate confirmation intake entry" :
    deliveredOrLater && !hasPod ? "Add a POD intake entry" :
    load.status === "IN_TRANSIT" && !hasBol ? "Add a BOL intake entry" :
    !hasFieldContext && fieldVisible > 0 ? "Confirm driver / truck field access context" :
    "Continue with controlled document access";

  return {
    tone,
    label,
    nextAction,
    splitHighlights,
    prompts,
  };
}

export function LoadDocumentAccessPanel({
  load,
  driver,
  truck,
  compact = false,
}: {
  load: Load;
  driver?: Driver | null;
  truck?: Truck | null;
  compact?: boolean;
}) {
  const [documents, setDocuments] = useState<LoadDocumentRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [form, setForm] = useState<DocumentFormValues>(emptyForm);

  async function loadDocuments() {
    if (!load.id || load.id === "draft-load-preview") {
      setDocuments([]);
      return;
    }

    try {
      setLoading(true);
      setError(null);
      const data = await apiGet<{ documents: LoadDocumentRecord[] }>(`/api/documents?loadId=${load.id}`);
      setDocuments(data.documents);
    } catch (err: any) {
      setError(err?.message ?? "Failed to load document intake records");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    loadDocuments();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [load.id]);

  const state = useMemo(() => getAccessHardeningState(load, documents, driver, truck), [documents, driver, load, truck]);
  const categoryState = useMemo(() => getDocumentCategoryEnforcementState(load, documents), [documents, load]);

  async function createDocumentIntakeEntry(event: React.FormEvent) {
    event.preventDefault();
    if (!load.id || load.id === "draft-load-preview") {
      setError("Save the load first so document intake entries can be created.");
      return;
    }
    if (!form.fileName.trim()) {
      setError("Document file name is required.");
      return;
    }

    try {
      setSaving(true);
      setError(null);
      await apiPost("/api/documents", {
        ...form,
        loadId: load.id,
        driverId: driver?.id || load.driver?.id || undefined,
        truckId: truck?.id || load.truck?.id || undefined,
      });
      setForm(emptyForm);
      await loadDocuments();
    } catch (err: any) {
      setError(err?.message ?? "Failed to create document intake entry");
    } finally {
      setSaving(false);
    }
  }

  return (
    <section className={`rounded-2xl border bg-white shadow-sm ${compact ? "p-4" : "p-6"}`}>
      <div className="mb-4">
        <h3 className="text-base font-semibold text-slate-900">Document-upload intake surface</h3>
        <p className="mt-1 text-sm text-slate-600">Field / office document visibility split, document-category enforcement prompts, invoice-package completeness visibility, and document-access workflow hardening for this load lifecycle.</p>
      </div>

      {error ? <div className="mb-4 rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">{error}</div> : null}

      <div className={`rounded-2xl border p-4 ${toneClasses(state.tone)}`}>
        <div className="text-xs font-semibold uppercase tracking-[0.18em]">Next document access action</div>
        <div className="mt-2 text-sm font-semibold">{state.nextAction}</div>
        <div className="mt-2 text-xs">Current control state: {state.label}</div>
      </div>

      <div className="mt-4 grid gap-3 md:grid-cols-3">
        {state.splitHighlights.map((item) => (
          <div key={item.label} className={`rounded-2xl border p-4 ${toneClasses(item.tone)}`}>
            <div className="text-xs font-semibold uppercase tracking-[0.16em]">{item.label}</div>
            <div className="mt-2 text-sm font-semibold">{item.value}</div>
          </div>
        ))}
      </div>

      <div className="mt-4 grid gap-4 xl:grid-cols-[1.05fr_0.95fr]">
        <div className="rounded-2xl border p-4">
          <div className="text-sm font-semibold text-slate-900">Document-upload intake surface</div>
          <p className="mt-1 text-sm text-slate-600">Log a document anchor with the visibility scope that matches who should be allowed to rely on it operationally.</p>
          <form className="mt-4 grid gap-3 md:grid-cols-2" onSubmit={createDocumentIntakeEntry}>
            <label className="block space-y-1 md:col-span-2">
              <span className="text-sm font-medium text-slate-700">Document file name</span>
              <input value={form.fileName} onChange={(e) => setForm((current) => ({ ...current, fileName: e.target.value }))} className="w-full rounded-xl border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-black/10" placeholder="rate-confirmation-1042.pdf" />
            </label>
            <label className="block space-y-1">
              <span className="text-sm font-medium text-slate-700">Category</span>
              <select value={form.category} onChange={(e) => setForm((current) => ({ ...current, category: e.target.value as Category }))} className="w-full rounded-xl border bg-white px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-black/10">
                {(["RATE_CONFIRMATION", "POD", "BOL", "RECEIPT", "SCALE_TICKET", "LUMPER_RECEIPT", "FUEL_RECEIPT", "GENERAL_ATTACHMENT", "OTHER"] as Category[]).map((category) => (
                  <option key={category} value={category}>{categoryLabel(category)}</option>
                ))}
              </select>
            </label>
            <label className="block space-y-1">
              <span className="text-sm font-medium text-slate-700">Visibility scope</span>
              <select value={form.visibilityScope} onChange={(e) => setForm((current) => ({ ...current, visibilityScope: e.target.value as VisibilityScope }))} className="w-full rounded-xl border bg-white px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-black/10">
                {(["INTERNAL_ONLY", "FIELD_VISIBLE", "ACCOUNTING_ONLY", "CUSTOMER_VISIBLE"] as VisibilityScope[]).map((scope) => (
                  <option key={scope} value={scope}>{visibilityLabel(scope)}</option>
                ))}
              </select>
            </label>
            <label className="block space-y-1 md:col-span-2">
              <span className="text-sm font-medium text-slate-700">Field label / note</span>
              <input value={form.fieldLabel} onChange={(e) => setForm((current) => ({ ...current, fieldLabel: e.target.value }))} className="w-full rounded-xl border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-black/10" placeholder="Broker signed rate con" />
            </label>
            <label className="flex items-center gap-2 text-sm text-slate-700 md:col-span-2">
              <input type="checkbox" checked={form.isFieldRequired} onChange={(e) => setForm((current) => ({ ...current, isFieldRequired: e.target.checked }))} className="h-4 w-4 rounded border-slate-300" />
              Mark this as field-required for the linked driver / truck path
            </label>
            <div className="md:col-span-2 flex justify-end">
              <button type="submit" disabled={saving || !load.id || load.id === "draft-load-preview"} className="rounded-xl bg-black px-4 py-2 text-sm font-medium text-white disabled:opacity-60">
                {saving ? "Saving..." : "Create intake entry"}
              </button>
            </div>
          </form>
        </div>

        <div className="rounded-2xl border p-4">
          <div className="text-sm font-semibold text-slate-900">Field / office document visibility split</div>
          <div className="mt-3 space-y-2 text-sm text-slate-700">
            {loading ? <div className="rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-slate-700">Loading document intake records...</div> : null}
            {!loading && documents.length === 0 ? <div className="rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-slate-700">No document intake records are attached to this load yet.</div> : null}
            {!loading && documents.map((document) => (
              <div key={document.id} className="rounded-xl border px-3 py-3">
                <div className="flex flex-wrap items-center gap-2">
                  <div className="font-medium text-slate-900">{document.fileName}</div>
                  <span className="rounded-full border bg-slate-50 px-2 py-0.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-600">{categoryLabel(document.category)}</span>
                  <span className="rounded-full border bg-slate-50 px-2 py-0.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-600">{visibilityLabel(document.visibilityScope as VisibilityScope)}</span>
                </div>
                <div className="mt-2 text-xs text-slate-500">{document.fieldLabel || "No field label"} • {formatDate(document.createdAt)}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="mt-4 grid gap-4 xl:grid-cols-[1fr_1fr]">
        <div className="rounded-2xl border p-4">
          <div className="text-sm font-semibold text-slate-900">Document-category enforcement prompts</div>
          <div className="mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-1">
            {categoryState.requirements.map((item) => (
              <div key={item.label} className={`rounded-xl border px-3 py-3 ${toneClasses(item.tone)}`}>
                <div className="text-xs font-semibold uppercase tracking-[0.16em]">{item.label}</div>
                <div className="mt-2 text-sm font-semibold">{item.complete ? "Ready" : "Follow-up needed"}</div>
                <div className="mt-1 text-xs">{item.detail}</div>
              </div>
            ))}
          </div>
          <div className="mt-3 space-y-2 text-sm text-slate-700">
            {categoryState.prompts.length ? categoryState.prompts.map((prompt) => (
              <div key={prompt} className="rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-amber-800">{prompt}</div>
            )) : <div className="rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-800">No document-category enforcement prompts remain on this workflow.</div>}
          </div>
        </div>

        <div className="rounded-2xl border p-4">
          <div className="text-sm font-semibold text-slate-900">Invoice-package completeness visibility</div>
          <p className="mt-1 text-sm text-slate-600">See whether the delivery-to-invoice package is complete enough for billing and closeout to move without guesswork.</p>
          <div className={`mt-3 rounded-2xl border p-4 ${toneClasses(categoryState.tone)}`}>
            <div className="text-xs font-semibold uppercase tracking-[0.18em]">Next invoice package action</div>
            <div className="mt-2 text-sm font-semibold">{categoryState.nextAction}</div>
          </div>
          <div className="mt-3 grid gap-3">
            {categoryState.packageChecks.map((item) => (
              <div key={item.label} className={`rounded-xl border px-3 py-3 ${toneClasses(item.tone)}`}>
                <div className="text-xs font-semibold uppercase tracking-[0.16em]">{item.label}</div>
                <div className="mt-2 text-sm font-semibold">{item.value}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="mt-4 rounded-2xl border p-4">
        <div className="text-sm font-semibold text-slate-900">Document-access workflow hardening</div>
        <div className="mt-3 space-y-2 text-sm text-slate-700">
          {state.prompts.length ? state.prompts.map((prompt) => (
            <div key={prompt} className="rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-amber-800">{prompt}</div>
          )) : <div className="rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-800">No document-access hardening prompts remain on this workflow.</div>}
        </div>
      </div>
    </section>
  );
}
