import { permissions } from "@mrp/shared";
import type { ShipmentDetailDto, ShipmentStatus, ShipmentSummaryDto } from "@mrp/shared/dist/shipping/types.js";
import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";

import { useAuth } from "../../auth/AuthProvider";
import { api, ApiError } from "../../lib/api";
import { ConfirmActionDialog } from "../../components/ConfirmActionDialog";
import { FileAttachmentsPanel } from "../../components/FileAttachmentsPanel";
import { shipmentStatusOptions } from "./config";
import { ShipmentStatusBadge } from "./ShipmentStatusBadge";

export function ShipmentDetailPage() {
  const { token, user } = useAuth();
  const { shipmentId } = useParams();
  const [shipment, setShipment] = useState<ShipmentDetailDto | null>(null);
  const [relatedShipments, setRelatedShipments] = useState<ShipmentSummaryDto[]>([]);
  const [status, setStatus] = useState("Loading shipment...");
  const [isUpdatingStatus, setIsUpdatingStatus] = useState(false);
  const [activeDocumentAction, setActiveDocumentAction] = useState<"packing-slip" | "label" | "bol" | null>(null);
  const [pendingConfirmation, setPendingConfirmation] = useState<
    | {
        title: string;
        description: string;
        impact: string;
        recovery: string;
        confirmLabel: string;
        confirmationLabel?: string;
        confirmationValue?: string;
        nextStatus: ShipmentStatus;
      }
    | null
  >(null);

  const canManage = user?.permissions.includes(permissions.shippingWrite) ?? false;

  useEffect(() => {
    if (!token || !shipmentId) {
      return;
    }

    api.getShipment(token, shipmentId)
      .then((nextShipment) => {
        setShipment(nextShipment);
        setStatus("Shipment loaded.");
        return api.getShipments(token, { salesOrderId: nextShipment.salesOrderId });
      })
      .then((shipments) => setRelatedShipments(shipments.filter((candidate) => candidate.id !== shipmentId)))
      .catch((error: unknown) => {
        const message = error instanceof ApiError ? error.message : "Unable to load shipment.";
        setStatus(message);
      });
  }, [shipmentId, token]);

  async function applyStatusChange(nextStatus: ShipmentStatus) {
    if (!token || !shipment) {
      return;
    }

    setIsUpdatingStatus(true);
    setStatus("Updating shipment status...");
    try {
      const nextShipment = await api.updateShipmentStatus(token, shipment.id, nextStatus);
      setShipment(nextShipment);
      setStatus("Shipment status updated. Verify carrier paperwork and sales-order expectations if the shipment moved into a terminal state.");
    } catch (error: unknown) {
      const message = error instanceof ApiError ? error.message : "Unable to update shipment status.";
      setStatus(message);
    } finally {
      setIsUpdatingStatus(false);
    }
  }

  function handleStatusChange(nextStatus: ShipmentStatus) {
    if (!shipment) {
      return;
    }

    const label = shipmentStatusOptions.find((option) => option.value === nextStatus)?.label ?? nextStatus;
    setPendingConfirmation({
      title: `Set shipment to ${label}`,
      description: `Update shipment ${shipment.shipmentNumber} from ${shipment.status} to ${nextStatus}.`,
      impact:
        nextStatus === "DELIVERED"
          ? "This marks delivery complete and can affect customer communication and project/shipping readiness views."
          : nextStatus === "SHIPPED"
            ? "This marks the shipment as outbound and can trigger customer-facing tracking and downstream delivery expectations."
            : "This changes the logistics state used by related shipping and sales workflows.",
      recovery: "If the status is wrong, return the shipment to the correct state and confirm the linked sales order still reflects reality.",
      confirmLabel: `Set ${label}`,
      confirmationLabel: nextStatus === "DELIVERED" ? "Type shipment number to confirm:" : undefined,
      confirmationValue: nextStatus === "DELIVERED" ? shipment.shipmentNumber : undefined,
      nextStatus,
    });
  }

  async function handleOpenDocument(kind: "packing-slip" | "label" | "bol") {
    if (!token || !shipment) {
      return;
    }

    setActiveDocumentAction(kind);
    setStatus(
      kind === "packing-slip"
        ? "Rendering packing slip PDF..."
        : kind === "label"
          ? "Rendering shipping label PDF..."
          : "Rendering bill of lading PDF..."
    );
    try {
      const blob =
        kind === "packing-slip"
          ? await api.getShipmentPackingSlipPdf(token, shipment.id)
          : kind === "label"
            ? await api.getShipmentLabelPdf(token, shipment.id)
            : await api.getShipmentBillOfLadingPdf(token, shipment.id);
      const objectUrl = URL.createObjectURL(blob);
      window.open(objectUrl, "_blank", "noopener,noreferrer");
      window.setTimeout(() => URL.revokeObjectURL(objectUrl), 60_000);
      setStatus(
        kind === "packing-slip"
          ? "Packing slip PDF rendered."
          : kind === "label"
            ? "Shipping label PDF rendered."
            : "Bill of lading PDF rendered."
      );
    } catch (error: unknown) {
      const message =
        error instanceof ApiError
          ? error.message
          : kind === "packing-slip"
            ? "Unable to render packing slip PDF."
            : kind === "label"
              ? "Unable to render shipping label PDF."
              : "Unable to render bill of lading PDF.";
      setStatus(message);
    } finally {
      setActiveDocumentAction(null);
    }
  }

  if (!shipment) {
    return <div className="rounded-[28px] border border-line/70 bg-surface/90 p-4 text-sm text-muted shadow-panel">{status}</div>;
  }

  return (
    <section className="space-y-4">
      <div className="rounded-[28px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Shipment</p>
            <h3 className="mt-2 text-xl font-bold text-text">{shipment.shipmentNumber}</h3>
            <p className="mt-1 text-sm text-text">{shipment.salesOrderNumber} · {shipment.customerName}</p>
            <div className="mt-3"><ShipmentStatusBadge status={shipment.status} /></div>
          </div>
          <div className="flex flex-wrap gap-3">
            <Link to="/shipping/shipments" className="inline-flex items-center justify-center rounded-2xl border border-line/70 px-2 py-2 text-sm font-semibold text-text">Back to shipments</Link>
            <Link to={`/sales/orders/${shipment.salesOrderId}`} className="inline-flex items-center justify-center rounded-2xl border border-line/70 px-2 py-2 text-sm font-semibold text-text">Open sales order</Link>
            <button type="button" onClick={() => handleOpenDocument("packing-slip")} disabled={activeDocumentAction !== null} className="inline-flex items-center justify-center rounded-2xl border border-line/70 px-2 py-2 text-sm font-semibold text-text disabled:cursor-not-allowed disabled:opacity-60">
              {activeDocumentAction === "packing-slip" ? "Rendering PDF..." : "Open packing slip"}
            </button>
            <button type="button" onClick={() => handleOpenDocument("label")} disabled={activeDocumentAction !== null} className="inline-flex items-center justify-center rounded-2xl border border-line/70 px-2 py-2 text-sm font-semibold text-text disabled:cursor-not-allowed disabled:opacity-60">
              {activeDocumentAction === "label" ? "Rendering PDF..." : "Open shipping label"}
            </button>
            <button type="button" onClick={() => handleOpenDocument("bol")} disabled={activeDocumentAction !== null} className="inline-flex items-center justify-center rounded-2xl border border-line/70 px-2 py-2 text-sm font-semibold text-text disabled:cursor-not-allowed disabled:opacity-60">
              {activeDocumentAction === "bol" ? "Rendering PDF..." : "Open bill of lading"}
            </button>
            {canManage ? (
              <Link to={`/shipping/shipments/${shipment.id}/edit`} className="inline-flex items-center justify-center rounded-2xl bg-brand px-2 py-2 text-sm font-semibold text-white">Edit shipment</Link>
            ) : null}
          </div>
        </div>
      </div>
      {canManage ? (
        <section className="rounded-[28px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Quick Actions</p>
              <p className="mt-2 text-sm text-muted">Update shipment status without opening the editor.</p>
            </div>
            <div className="flex flex-wrap gap-2">
              {shipmentStatusOptions.map((option) => (
                <button key={option.value} type="button" onClick={() => handleStatusChange(option.value)} disabled={isUpdatingStatus || shipment.status === option.value} className="rounded-2xl border border-line/70 px-2 py-2 text-sm font-semibold text-text disabled:cursor-not-allowed disabled:opacity-60">
                  {option.label}
                </button>
              ))}
            </div>
          </div>
        </section>
      ) : null}
      <section className="grid gap-3 xl:grid-cols-4">
        <article className="rounded-[24px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Carrier</p><div className="mt-2 text-base font-bold text-text">{shipment.carrier || "Not set"}</div></article>
        <article className="rounded-[24px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Service</p><div className="mt-2 text-base font-bold text-text">{shipment.serviceLevel || "Not set"}</div></article>
        <article className="rounded-[24px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Tracking</p><div className="mt-2 text-base font-bold text-text">{shipment.trackingNumber || "Not set"}</div></article>
        <article className="rounded-[24px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Packages</p><div className="mt-2 text-base font-bold text-text">{shipment.packageCount}</div></article>
      </section>
      <div className="grid gap-3 xl:grid-cols-[minmax(0,1fr)_minmax(320px,0.9fr)]">
        <article className="rounded-[28px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Shipment Notes</p>
          <p className="mt-3 whitespace-pre-line text-sm leading-6 text-text">{shipment.notes || "No notes recorded for this shipment."}</p>
        </article>
        <article className="rounded-[28px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Timing</p>
          <dl className="mt-5 grid gap-3">
            <div><dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Ship Date</dt><dd className="mt-1 text-sm text-text">{shipment.shipDate ? new Date(shipment.shipDate).toLocaleDateString() : "Not set"}</dd></div>
            <div><dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Created</dt><dd className="mt-1 text-sm text-text">{new Date(shipment.createdAt).toLocaleString()}</dd></div>
            <div><dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Updated</dt><dd className="mt-1 text-sm text-text">{new Date(shipment.updatedAt).toLocaleString()}</dd></div>
          </dl>
        </article>
      </div>
      <section className="rounded-[28px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
        <div className="flex items-center justify-between gap-3">
          <div>
            <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Related Shipments</p>
            <p className="mt-2 text-sm text-muted">Other shipments already tied to this sales order.</p>
          </div>
          {canManage ? (
            <Link to={`/shipping/shipments/new?orderId=${shipment.salesOrderId}`} className="inline-flex items-center justify-center rounded-2xl border border-line/70 px-2 py-2 text-sm font-semibold text-text">Add another shipment</Link>
          ) : null}
        </div>
        {relatedShipments.length === 0 ? (
          <div className="mt-6 rounded-3xl border border-dashed border-line/70 bg-page/60 px-4 py-8 text-center text-sm text-muted">No additional shipments exist for this sales order.</div>
        ) : (
          <div className="mt-6 space-y-3">
            {relatedShipments.map((related) => (
              <Link key={related.id} to={`/shipping/shipments/${related.id}`} className="block rounded-3xl border border-line/70 bg-page/60 p-3 transition hover:bg-page/80">
                <div className="flex flex-wrap items-center justify-between gap-3">
                  <div>
                    <div className="font-semibold text-text">{related.shipmentNumber}</div>
                    <div className="mt-1 text-xs text-muted">{related.carrier || "Carrier not set"} · {related.trackingNumber || "No tracking"}</div>
                  </div>
                  <ShipmentStatusBadge status={related.status} />
                </div>
              </Link>
            ))}
          </div>
        )}
      </section>
      <FileAttachmentsPanel
        ownerType="SHIPMENT"
        ownerId={shipment.id}
        eyebrow="Logistics Attachments"
        title="Shipment files"
        description="Store carrier paperwork, signed delivery records, bills of lading, and related logistics support files on the shipment record."
        emptyMessage="No logistics attachments have been uploaded for this shipment yet."
      />
      <ConfirmActionDialog
        open={pendingConfirmation != null}
        title={pendingConfirmation?.title ?? "Confirm shipment action"}
        description={pendingConfirmation?.description ?? ""}
        impact={pendingConfirmation?.impact}
        recovery={pendingConfirmation?.recovery}
        confirmLabel={pendingConfirmation?.confirmLabel ?? "Confirm"}
        confirmationLabel={pendingConfirmation?.confirmationLabel}
        confirmationValue={pendingConfirmation?.confirmationValue}
        isConfirming={isUpdatingStatus}
        onClose={() => {
          if (!isUpdatingStatus) {
            setPendingConfirmation(null);
          }
        }}
        onConfirm={async () => {
          if (!pendingConfirmation) {
            return;
          }

          await applyStatusChange(pendingConfirmation.nextStatus);
          setPendingConfirmation(null);
        }}
      />
    </section>
  );
}
