import { Box, Group, Stack, Text } from "@mantine/core";
import {
  AlertTriangle,
  Check,
  CircleDot,
  FileEdit,
  FilePlus2,
  Gavel,
  PenLine,
  Send,
  ShieldCheck,
  Truck,
  XCircle,
} from "lucide-react";
import type { LucideIcon } from "lucide-react";
import type { Freight } from "@edr/types";

import {
  BORDER,
  GREEN,
  GREEN_DARK,
  INK,
  MUTED,
  expiryNoticeDays,
} from "./contract-ui";

/**
 * The customer-facing contract journey, in order. This is the *contract track*
 * (establishing the agreement) — the per-shipment booking/clearance journey is a
 * separate stepper (`ClearancePhaseStepper`) shown on a booking, not here.
 */
interface Stage {
  key: string;
  label: string;
  icon: LucideIcon;
}

const STAGES: Stage[] = [
  { key: "draft", label: "Draft", icon: FileEdit },
  { key: "submitted", label: "Submitted", icon: Send },
  { key: "accepted", label: "Accepted", icon: ShieldCheck },
  { key: "approval", label: "Approval", icon: Gavel },
  { key: "sign", label: "Signature", icon: PenLine },
  { key: "active", label: "Active", icon: FilePlus2 },
  { key: "shipping", label: "Shipping", icon: Truck },
];

const STAGE_INDEX: Record<string, number> = STAGES.reduce(
  (acc, s, i) => ({ ...acc, [s.key]: i }),
  {},
);

type Terminal = "REJECTED" | "CANCELLED" | "EXPIRED" | "CLOSED" | null;

interface StepState {
  /** Index into STAGES of the stage the contract is currently working on. */
  activeIdx: number;
  /** Terminal state, if the contract ended off the happy path. */
  terminal: Terminal;
  /** One-line "what happens next" helper for the customer. */
  next: string;
}

/**
 * Map any contract status onto the journey. Statuses that share a stage (e.g.
 * every approval/signature sub-state) collapse onto that stage; the helper line
 * is what disambiguates them for the customer.
 */
function resolveStep(status: string): StepState {
  const at = (key: string): number => STAGE_INDEX[key] ?? 0;

  switch (status) {
    case "DRAFT":
    case "RENEWAL_DRAFT":
      return { activeIdx: at("draft"), terminal: null, next: "Finish and submit this contract for review." };

    case "SUBMITTED":
    case "RENEWAL_SUBMITTED":
      return { activeIdx: at("submitted"), terminal: null, next: "Waiting for staff to accept your submission." };

    case "PRICE_CHANGED_PENDING_CONFIRM":
      return { activeIdx: at("submitted"), terminal: null, next: "Price changed since preview — confirm to resubmit." };

    case "CHANGES_REQUESTED":
      return { activeIdx: at("submitted"), terminal: null, next: "Staff requested changes — update and resubmit." };

    case "AMENDMENTS_PROPOSED":
      return { activeIdx: at("submitted"), terminal: null, next: "Amendments proposed — review the proposed changes." };

    case "PENDING_APPROVAL":
    case "RENEWAL_PENDING_APPROVAL":
      return { activeIdx: at("approval"), terminal: null, next: "Under internal approval (staff → director → CEO)." };

    case "APPROVED":
      return { activeIdx: at("approval"), terminal: null, next: "Approved — the contract document is being prepared." };

    case "APPROVED_PENDING_SIGNATURE":
    case "CONTRACT_READY":
      return { activeIdx: at("sign"), terminal: null, next: "Contract is ready — review and sign it." };

    case "SIGNED_CUSTOMER":
      return { activeIdx: at("sign"), terminal: null, next: "You've signed — waiting for staff to counter-sign." };

    case "CONTRACT_ACTIVE":
    case "FULLY_EXECUTED":
    case "CLEARANCE_READY_FOR_BOOKING":
      return { activeIdx: at("active"), terminal: null, next: "Active — submit a shipment request to start shipping." };

    case "AWAITING_CLEARANCE_DOCUMENTS":
      return { activeIdx: at("active"), terminal: null, next: "Upload the pre-booking clearance documents." };

    case "CLEARANCE_UNDER_REVIEW":
      return { activeIdx: at("active"), terminal: null, next: "Global Logistics is reviewing your clearance documents." };

    case "ACTIVE_SHIPMENT_IN_PROGRESS":
      return { activeIdx: at("shipping"), terminal: null, next: "A shipment is in progress under this contract." };

    // ── Terminal ──
    case "REJECTED":
      return { activeIdx: at("approval"), terminal: "REJECTED", next: "This contract was rejected." };
    case "CANCELLED":
      return { activeIdx: at("draft"), terminal: "CANCELLED", next: "This contract was cancelled." };
    case "EXPIRED":
      return { activeIdx: at("active"), terminal: "EXPIRED", next: "This contract's validity has expired." };
    case "CONTRACT_CLOSED":
    case "ARCHIVED":
      return { activeIdx: STAGES.length - 1, terminal: "CLOSED", next: "This contract is closed." };

    default:
      return { activeIdx: at("draft"), terminal: null, next: "" };
  }
}

export interface ContractStepBannerProps {
  contract: Freight.IContract;
}

/**
 * A polished, branded step banner that shows where a contract sits in its
 * lifecycle. Rendered inside the expanded region of a contract row.
 */
export function ContractStepBanner({ contract }: ContractStepBannerProps) {
  const { activeIdx, terminal, next } = resolveStep(contract.status);
  const isTerminalBad = terminal === "REJECTED" || terminal === "CANCELLED" || terminal === "EXPIRED";

  // Same notice window as the list badge and the API's reminder.
  const expiryDays = expiryNoticeDays(contract);
  const expirySoon = !terminal && expiryDays !== null;

  return (
    <Box
      style={{
        borderRadius: 14,
        padding: "18px 20px",
        border: `1px solid ${isTerminalBad ? "#F3C6C1" : BORDER}`,
        background: isTerminalBad
          ? "linear-gradient(135deg, #FEF3F2 0%, #FFFFFF 60%)"
          : `linear-gradient(135deg, ${GREEN}12 0%, ${GREEN}06 26%, #FFFFFF 68%)`,
      }}
    >
      {/* Stepper row */}
      <Group gap={0} wrap="nowrap" align="flex-start" style={{ overflowX: "auto" }}>
        {STAGES.map((stage, index) => {
          const isComplete = !isTerminalBad && index < activeIdx;
          const isActive = !isTerminalBad && index === activeIdx;
          const isFailedHere = isTerminalBad && index === activeIdx;
          const isLast = index === STAGES.length - 1;
          const Icon = isFailedHere ? XCircle : stage.icon;

          return (
            <Box key={stage.key} style={{ flex: isLast ? "0 0 auto" : 1, minWidth: 78 }}>
              <Group gap={0} wrap="nowrap" align="center">
                <Stack gap={5} align="center" style={{ flexShrink: 0 }}>
                  <Box
                    style={{
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      width: 36,
                      height: 36,
                      borderRadius: "50%",
                      background: isComplete
                        ? GREEN_DARK
                        : isFailedHere
                          ? "#D92D20"
                          : isActive
                            ? "#FFFFFF"
                            : "#F1F5F8",
                      border: isActive
                        ? `2px solid ${GREEN}`
                        : isComplete || isFailedHere
                          ? "2px solid transparent"
                          : `2px solid ${BORDER}`,
                      color: isComplete || isFailedHere
                        ? "#FFFFFF"
                        : isActive
                          ? GREEN_DARK
                          : "#9AA9B7",
                      boxShadow: isActive ? `0 0 0 4px ${GREEN}22` : "none",
                      transition: "all 160ms ease",
                    }}
                  >
                    {isComplete ? (
                      <Check size={17} strokeWidth={3} />
                    ) : (
                      <Icon size={17} strokeWidth={isActive ? 2.4 : 2} />
                    )}
                  </Box>
                  <Text
                    fz={11}
                    fw={isActive ? 700 : 600}
                    ta="center"
                    style={{
                      whiteSpace: "nowrap",
                      color: isActive ? GREEN_DARK : isComplete ? INK : MUTED,
                    }}
                  >
                    {stage.label}
                  </Text>
                </Stack>
                {!isLast && (
                  <Box
                    style={{
                      flex: 1,
                      height: 2.5,
                      marginInline: 6,
                      marginBottom: 20,
                      borderRadius: 2,
                      background: isComplete ? GREEN_DARK : BORDER,
                      transition: "background 160ms ease",
                    }}
                  />
                )}
              </Group>
            </Box>
          );
        })}
      </Group>

      {/* Helper line + expiry hint */}
      {(next || expirySoon) && (
        <Group gap={16} wrap="wrap" mt={14} align="center">
          {next && (
            <Group gap={7} wrap="nowrap" align="center">
              {isTerminalBad ? (
                <XCircle size={15} color="#D92D20" />
              ) : (
                <CircleDot size={15} color={GREEN_DARK} />
              )}
              <Text fz={12.5} fw={600} style={{ color: isTerminalBad ? "#B42318" : INK }}>
                {next}
              </Text>
            </Group>
          )}
          {contract.status === "REJECTED" && contract.latestRejectionNote && (
            <Text
              fz={12.5}
              style={{ color: "#B42318", whiteSpace: "pre-wrap", width: "100%" }}
            >
              Reason: {contract.latestRejectionNote}
            </Text>
          )}
          {expirySoon && (
            <Group gap={6} wrap="nowrap" align="center">
              <AlertTriangle size={14} color="#9A6700" />
              <Text fz={12} fw={600} c="#9A6700">
                {expiryDays === 0
                  ? "Validity ends today"
                  : `Validity ends in ${expiryDays} day${expiryDays === 1 ? "" : "s"}`}
              </Text>
            </Group>
          )}
        </Group>
      )}
    </Box>
  );
}
