import { Box, Group, Stack, Text, Tooltip } from "@mantine/core";
import { Fragment } from "react";
import {
  moduleLabel,
  eventTypeLabel,
  type EventRecord,
} from "@/lib/features/event-analytics/types";

export function buildJourneyIndex(
  records: EventRecord[],
): Map<string, EventRecord> {
  const supersededBy = new Map<string, EventRecord>();
  for (const record of records) {
    for (const earlier of [record.addToCartId, record.bookingHoldId]) {
      if (!earlier) continue;
      const existing = supersededBy.get(earlier);
      if (!existing || rank(record.eventType) > rank(existing.eventType)) {
        supersededBy.set(earlier, record);
      }
    }
  }
  return supersededBy;
}

const STEP_ORDER = ["add_to_cart", "booking_hold_initiated", "purchase"];
const rank = (eventType: string) => {
  const i = STEP_ORDER.indexOf(eventType);
  return i === -1 ? STEP_ORDER.length : i;
};

const MONTHS = [
  "Jan",
  "Feb",
  "Mar",
  "Apr",
  "May",
  "Jun",
  "Jul",
  "Aug",
  "Sep",
  "Oct",
  "Nov",
  "Dec",
];

function formatTime(iso: string | null): string | null {
  if (!iso) return null;
  const m = /[T ](\d{2}):(\d{2}):(\d{2})/.exec(iso);
  return m ? `${m[1]}:${m[2]}:${m[3]}` : iso;
}

function formatDay(iso: string | null): string | null {
  if (!iso) return null;
  const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso);
  return m ? `${m[3]} ${MONTHS[Number(m[2]) - 1] ?? m[2]}` : iso;
}

function formatStampShort(iso: string | null): string | null {
  if (!iso) return null;
  const m = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})/.exec(iso);
  if (!m) return iso;
  const [, , mo, d, hh, mm] = m;
  return `${d} ${MONTHS[Number(mo) - 1] ?? mo} ${hh}:${mm}`;
}

function formatStamp(iso: string | null): string | null {
  if (!iso) return null;
  const m = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})/.exec(iso);
  if (!m) return iso;
  const [, y, mo, d, hh, mm, ss] = m;
  const month = MONTHS[Number(mo) - 1] ?? mo;
  return `${d} ${month} ${y} · ${hh}:${mm}:${ss}`;
}

function hoursBetween(from: string | null, to: string | null): number | null {
  if (!from || !to) return null;
  const a = Date.parse(from);
  const b = Date.parse(to);
  if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
  const hours = (b - a) / 3_600_000;
  return hours >= 0 ? hours : null;
}

function formatGap(hours: number): string {
  const seconds = hours * 3600;
  if (seconds < 60) return `${Math.max(1, Math.round(seconds))}s`;
  if (hours < 1) return `${Math.round(hours * 60)}m`;
  if (hours < 24) {
    const h = Math.floor(hours);
    const m = Math.round((hours - h) * 60);
    return m ? `${h}h ${m}m` : `${h}h`;
  }
  const d = Math.floor(hours / 24);
  const h = Math.round(hours % 24);
  return h ? `${d}d ${h}h` : `${d}d`;
}

export default function JourneyStrip({
  record,
  supersededBy,
  variant = "full",
}: {
  record: EventRecord;
  supersededBy?: EventRecord;
  variant?: "full" | "inline";
}) {
  if (variant === "inline") {
    const purchaseAt =
      record.eventType === "purchase" ? record.occurredAt : null;
    const steps = [
      { key: "add_to_cart", short: "Cart", at: record.addToCartAt },
      {
        key: "booking_hold_initiated",
        short: "Hold",
        at: record.bookingHoldAt,
      },
      { key: "purchase", short: "Purchase", at: purchaseAt },
    ].map((step) =>
      step.key === record.eventType && !step.at
        ? { ...step, at: record.occurredAt }
        : step,
    );

    const days = [
      ...new Set(steps.map((s) => formatDay(s.at)).filter(Boolean)),
    ];
    const singleDay = days.length === 1 ? days[0] : null;

    return (
      <Group gap="xs" wrap="nowrap" align="center">
        {singleDay && (
          <Text size="xs" c="dimmed" fw={500} style={{ whiteSpace: "nowrap" }}>
            {singleDay}
          </Text>
        )}
        <Group gap={0} wrap="nowrap" align="flex-start">
          {steps.map((step, i) => {
            const reached = Boolean(step.at);
            const isCurrent = step.key === record.eventType;
            const gap = i > 0 ? hoursBetween(steps[i - 1].at, step.at) : null;
            return (
              <Fragment key={step.key}>
                {i > 0 && (
                  <Stack gap={0} align="center" style={{ width: 46 }} mt={4}>
                    <Box
                      style={{
                        height: 2,
                        width: "100%",
                        background: reached
                          ? "var(--mantine-color-teal-4)"
                          : "var(--mantine-color-gray-3)",
                      }}
                    />
                    <Text size="xs" c="dimmed" lh={1.3}>
                      {gap !== null ? formatGap(gap) : ""}
                    </Text>
                  </Stack>
                )}
                <Tooltip
                  label={`${eventTypeLabel(step.key)} — ${formatStamp(step.at) ?? "not reached"}`}
                >
                  <Stack gap={1} align="center" style={{ minWidth: 62 }}>
                    <Box
                      style={{
                        width: 10,
                        height: 10,
                        borderRadius: "50%",
                        flexShrink: 0,
                        border: `2px solid ${
                          reached
                            ? "var(--mantine-color-teal-6)"
                            : "var(--mantine-color-gray-4)"
                        }`,
                        background: reached
                          ? isCurrent
                            ? "var(--mantine-color-teal-6)"
                            : "var(--mantine-color-teal-1)"
                          : "transparent",
                      }}
                    />
                    <Text
                      size="xs"
                      c={reached ? undefined : "dimmed"}
                      fw={isCurrent ? 600 : 400}
                      lh={1.3}
                      style={{ fontVariantNumeric: "tabular-nums" }}
                    >
                      {(singleDay
                        ? formatTime(step.at)
                        : formatStampShort(step.at)) ?? "—"}
                    </Text>
                    <Text size="xs" c="dimmed" lh={1.2}>
                      {step.short}
                    </Text>
                  </Stack>
                </Tooltip>
              </Fragment>
            );
          })}
        </Group>
      </Group>
    );
  }

  if (supersededBy) {
    return (
      <Stack gap={4} p="md">
        <Text size="xs" c="dimmed" tt="uppercase" fw={600}>
          Journey
        </Text>
        <Text size="sm">
          Part of the {eventTypeLabel(supersededBy.eventType).toLowerCase()}{" "}
          journey
          {supersededBy.occurredAt
            ? ` on ${formatStamp(supersededBy.occurredAt)}`
            : ""}{" "}
          — shown there in full.
        </Text>
        <Text size="xs" c="dimmed" ff="monospace">
          {supersededBy.id}
        </Text>
      </Stack>
    );
  }

  const purchaseAt = record.eventType === "purchase" ? record.occurredAt : null;
  const steps = [
    { key: "add_to_cart", at: record.addToCartAt, id: record.addToCartId },
    {
      key: "booking_hold_initiated",
      at: record.bookingHoldAt,
      id: record.bookingHoldId,
    },
    { key: "purchase", at: purchaseAt, id: null as string | null },
  ];

  const resolved = steps.map((step) =>
    step.key === record.eventType && !step.at
      ? { ...step, at: record.occurredAt }
      : step,
  );

  return (
    <Stack gap="md" p="md">
      <Group gap="xs" align="center">
        <Text size="xs" c="dimmed" tt="uppercase" fw={600}>
          Journey
        </Text>
        {record.journeyId ? (
          <Text size="xs" c="dimmed" ff="monospace">
            {record.journeyId}
          </Text>
        ) : (
          <Text size="xs" c="dimmed">
            steps inferred from this event
          </Text>
        )}
      </Group>

      <Group gap={0} align="flex-start" wrap="nowrap">
        {resolved.map((step, i) => {
          const reached = Boolean(step.at);
          const isCurrent = step.key === record.eventType;
          const gap = i > 0 ? hoursBetween(resolved[i - 1].at, step.at) : null;
          return (
            <Fragment key={step.key}>
              {i > 0 && (
                <Stack
                  gap={2}
                  align="center"
                  style={{ flex: 1, minWidth: 64 }}
                  mt={7}
                >
                  <Box
                    style={{
                      height: 2,
                      width: "100%",
                      background: reached
                        ? "var(--mantine-color-teal-4)"
                        : "var(--mantine-color-gray-3)",
                    }}
                  />
                  <Text size="xs" c="dimmed" ta="center">
                    {gap !== null ? formatGap(gap) : reached ? "—" : ""}
                  </Text>
                </Stack>
              )}

              <Stack gap={4} align="center" style={{ minWidth: 132 }}>
                <Box
                  style={{
                    width: 16,
                    height: 16,
                    borderRadius: "50%",
                    border: `2px solid ${
                      reached
                        ? "var(--mantine-color-teal-6)"
                        : "var(--mantine-color-gray-4)"
                    }`,
                    background: reached
                      ? isCurrent
                        ? "var(--mantine-color-teal-6)"
                        : "var(--mantine-color-teal-1)"
                      : "transparent",
                  }}
                />
                <Text size="sm" fw={isCurrent ? 700 : 500} ta="center">
                  {eventTypeLabel(step.key)}
                </Text>
                <Text size="xs" c="dimmed" ta="center">
                  {formatStamp(step.at) ?? "not reached"}
                </Text>
              </Stack>
            </Fragment>
          );
        })}
      </Group>

      <Group gap="xl">
        <Stack gap={0}>
          <Text size="xs" c="dimmed" tt="uppercase" fw={600}>
            Source
          </Text>
          <Text size="sm">{moduleLabel(record.source)}</Text>
        </Stack>
        <Stack gap={0}>
          <Text size="xs" c="dimmed" tt="uppercase" fw={600}>
            Channel
          </Text>
          <Text size="sm">
            {record.utmSource
              ? `${record.utmSource}${record.utmMedium ? ` / ${record.utmMedium}` : ""}`
              : "Direct"}
          </Text>
        </Stack>
        {record.propertyName && (
          <Stack gap={0}>
            <Text size="xs" c="dimmed" tt="uppercase" fw={600}>
              Property
            </Text>
            <Text size="sm">{record.propertyName}</Text>
          </Stack>
        )}
      </Group>
    </Stack>
  );
}
