import { Box, Group, Text } from "@mantine/core";
import {
  AlertTriangle,
  Check,
  FileText,
  History,
  MapPin,
  MoveRight,
} from "lucide-react";

import type { Freight } from "@edr/types";

import { PROGRESS_STAGES, STATUS_MAP } from "../constants";
import { fmtDate, isDraftLike, isNegative, yardLabel } from "../utils";
import { SectionCard } from "./layout";

const ACCENT = "#F2A516";

/** Origin → destination strip rendered above the progress tracker. */
function RouteStrip({ booking }: { booking: Freight.IBooking }) {
  const origin = yardLabel(booking.originYard);
  const destination = yardLabel(booking.destinationYard);
  return (
    <Box
      mb={22}
      px={18}
      py={14}
      className="rounded-2xl"
      style={{
        background:
          "linear-gradient(135deg, #FEF8EC 0%, #FBFCFD 60%, #F4FAF7 100%)",
        border: "1px solid #F2E4C4",
      }}
    >
      <Group justify="space-between" align="center" wrap="nowrap" gap="md">
        <RouteEndpoint label="Origin" value={origin} />
        <Box
          className="flex items-center justify-center rounded-full shrink-0"
          style={{
            width: 34,
            height: 34,
            backgroundColor: "#fff",
            border: `1px solid ${ACCENT}33`,
            color: ACCENT,
          }}
        >
          <MoveRight size={18} />
        </Box>
        <RouteEndpoint label="Destination" value={destination} alignRight />
      </Group>
    </Box>
  );
}

function RouteEndpoint({
  label,
  value,
  alignRight,
}: {
  label: string;
  value: string;
  alignRight?: boolean;
}) {
  return (
    <Box miw={0} style={{ textAlign: alignRight ? "right" : "left", flex: 1 }}>
      <Group
        gap={5}
        align="center"
        wrap="nowrap"
        justify={alignRight ? "flex-end" : "flex-start"}
      >
        <MapPin size={12} color={ACCENT} />
        <Text
          fz="10.5px"
          fw={700}
          c="#B07D14"
          tt="uppercase"
          className="tracking-[0.6px]"
        >
          {label}
        </Text>
      </Group>
      <Text mt={3} fz="15px" fw={800} c="#10202F" truncate>
        {value}
      </Text>
    </Box>
  );
}

export function StatusHero({
  booking,
  children,
}: {
  booking: Freight.IBooking;
  children?: React.ReactNode;
}) {
  const status = booking.status;
  const cfg = STATUS_MAP[status] ?? STATUS_MAP.DRAFT;
  const negative = isNegative(status);
  const draft = isDraftLike(status);

  const tone: "green" | "slate" | "red" = negative
    ? "red"
    : draft
      ? "slate"
      : "green";
  const tileBg =
    tone === "red" ? "#FBEAE7" : tone === "slate" ? "#F1F4F7" : "#ECF6F1";
  const tileFg =
    tone === "red" ? "#C0392B" : tone === "slate" ? "#475569" : "#0EA371";
  const HeroIcon = negative
    ? AlertTriangle
    : draft
      ? FileText
      : (PROGRESS_STAGES[cfg.stage]?.icon ?? History);

  const chipLabel = draft ? "Last edited" : negative ? "Updated" : "Scheduled";
  const chipValue = fmtDate(
    draft || negative ? booking.updatedAt : booking.scheduledDate,
  );

  return (
    <SectionCard p={28}>
      <Group justify="space-between" align="center" wrap="wrap" gap="md">
        <Group gap={16} align="center" wrap="nowrap">
          <div
            className="flex items-center justify-center rounded-2xl shrink-0"
            style={{
              width: 56,
              height: 56,
              backgroundColor: tileBg,
              color: tileFg,
            }}
          >
            <HeroIcon size={26} />
          </div>
          <Box>
            <Text fz="21px" fw={800} c="#10202F">
              {cfg.title}
            </Text>
            <Text mt={5} fz="14px" c="#6B7C8E">
              {cfg.description}
            </Text>
          </Box>
        </Group>
        <Group
          gap={11}
          align="center"
          wrap="nowrap"
          px="md"
          py="sm"
          className="rounded-[14px] border border-[#E6ECF2] bg-[#F7FAFC]"
        >
          <History size={22} color="#64748B" />
          <Box>
            <Text
              fz="10.5px"
              fw={700}
              c="#9AA8B5"
              tt="uppercase"
              className="tracking-[0.6px]"
            >
              {chipLabel}
            </Text>
            <Text fz="sm" fw={700} c="#10202F">
              {chipValue}
            </Text>
          </Box>
        </Group>
      </Group>

      <Box my={26} h={1} w="100%" bg="#EEF2F6" />

      {!negative && <RouteStrip booking={booking} />}

      {children ?? (
        <ProgressTracker
          current={cfg.stage}
          tone={draft ? "ink" : "green"}
          negative={negative}
        />
      )}
    </SectionCard>
  );
}

function ProgressTracker({
  current,
  tone = "green",
}: {
  current: number;
  tone?: "green" | "ink";
  negative?: boolean;
}) {
  const last = PROGRESS_STAGES.length - 1;
  const activeFill = tone === "ink" ? "#0C1A2B" : "#0EA371";
  const activeRing = tone === "ink" ? "#D9E0E7" : "#BFE8D4";

  return (
    /* Scrollable on mobile so 5 stages never overflow */
    <Box
      className="overflow-x-auto pt-2"
      style={
        {
          scrollbarWidth: "none",
          WebkitOverflowScrolling: "touch",
        } as React.CSSProperties
      }
    >
      <div className="flex items-start" style={{ minWidth: 440 }}>
        {PROGRESS_STAGES.map((stage, idx) => {
          const state =
            idx < current ? "done" : idx === current ? "active" : "idle";
          const Icon = stage.icon;
          const reachedLeft = current >= idx && current >= 0;
          const reachedRight = current > idx && current >= 0;

          const circleBg =
            state === "idle"
              ? "#EEF2F6"
              : state === "active"
                ? activeFill
                : "#0EA371";
          const circleBorder =
            state === "idle" ? "1px solid #E1E7EE" : undefined;
          const circleShadow =
            state === "active" ? `0 0 0 4px ${activeRing}` : undefined;

          return (
            <div
              key={stage.label}
              className="flex flex-1 flex-col items-center"
            >
              <div className="flex w-full items-center">
                {/* left connector */}
                <div
                  className="flex-1 rounded-full"
                  style={{
                    height: 3,
                    background:
                      idx === 0
                        ? "transparent"
                        : reachedLeft
                          ? "#0EA371"
                          : "#E1E7EE",
                  }}
                />
                {/* stage circle */}
                <div
                  className="flex items-center justify-center mb-2 rounded-full shrink-0"
                  style={{
                    width: 32,
                    height: 32,
                    backgroundColor: circleBg,
                    border: circleBorder,
                    boxShadow: circleShadow,
                  }}
                >
                  {state === "done" ? (
                    <Check size={16} color="#fff" />
                  ) : state === "active" ? (
                    <Icon size={16} color="#fff" />
                  ) : null}
                </div>
                {/* right connector */}
                <div
                  className="flex-1 rounded-full"
                  style={{
                    height: 3,
                    background:
                      idx === last
                        ? "transparent"
                        : reachedRight
                          ? "#0EA371"
                          : "#E1E7EE",
                  }}
                />
              </div>
              <Text
                fz="14px"
                fw={700}
                ta="center"
                c={state === "idle" ? "#9AA8B5" : "#10202F"}
              >
                {stage.label}
              </Text>
            </div>
          );
        })}
      </div>
    </Box>
  );
}
