"use client";

import PoWorkbenchReceiveStatusChip from "@/components/PoWorkbench/shared/PoWorkbenchReceiveStatusChip";
import {
  PO_WORKBENCH_META_ICON_SX,
  PO_WORKBENCH_RESULT_LINE_SX,
} from "@/components/PoWorkbench/shared/poWorkbenchSharedStyles";
import type { PoWorkbenchListRow } from "@/components/PoWorkbench/types";
import CalendarTodayIcon from "@mui/icons-material/CalendarToday";
import LocalShippingIcon from "@mui/icons-material/LocalShipping";
import Chip from "@mui/material/Chip";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { useMediaQuery, useTheme } from "@mui/material";
import { useTranslation } from "react-i18next";

const DATE_ROW_SX = {
  direction: "row" as const,
  spacing: 2,
  flexWrap: "wrap" as const,
  alignItems: "center" as const,
};

export function formatDateYmd(value: unknown): string {
  if (typeof value !== "string") {
    return "";
  }
  const normalized = value.trim();
  if (/^\d{4}-\d{2}-\d{2}$/.test(normalized)) {
    return normalized;
  }
  const d = new Date(normalized);
  if (Number.isNaN(d.getTime())) {
    return normalized;
  }
  return d.toISOString().slice(0, 10);
}

type DateKind = "order" | "eta";

interface DateSegmentProps {
  kind: DateKind;
  dateYmd: string;
}

/** List / header: icon plus date; same `body2` size as supplier line. */
function WorkbenchResultDateSegment({ kind, dateYmd }: DateSegmentProps) {
  const icon =
    kind === "order" ? (
      <CalendarTodayIcon sx={PO_WORKBENCH_META_ICON_SX} />
    ) : (
      <LocalShippingIcon sx={PO_WORKBENCH_META_ICON_SX} />
    );
  return (
    <Stack direction="row" spacing={0.75} alignItems="center">
      {icon}
      <Typography variant="body2" color="text.secondary" sx={PO_WORKBENCH_RESULT_LINE_SX}>
        {dateYmd}
      </Typography>
    </Stack>
  );
}

export interface PoWorkbenchResultSummaryProps {
  row: PoWorkbenchListRow;
  /** `header`: PO + supplier left; status chips then dates on the right. `list`: list row. */
  layout?: "list" | "header";
}

/** @deprecated Use {@link PoWorkbenchResultSummaryProps}. */
export type WorkbenchResultSummaryProps = PoWorkbenchResultSummaryProps;

interface PoSupplierBlockProps {
  row: PoWorkbenchListRow;
}

interface EtaVarianceReminder {
  color: "primary" | "warning";
  label: string;
}

const HEADER_LINE_CLAMP_SX = {
  overflow: "hidden",
  textOverflow: "ellipsis",
  whiteSpace: "nowrap",
  minWidth: 0,
} as const;

const ETA_VARIANCE_CHIP_SX = {
  height: "auto",
  minHeight: 26,
  fontWeight: 600,
  lineHeight: 1.25,
  "& .MuiChip-label": {
    px: 1,
    py: 0.25,
    display: "block",
  },
} as const;

function startOfLocalDay(value: Date): Date {
  return new Date(value.getFullYear(), value.getMonth(), value.getDate());
}

/** `YYYY-MM-DD` → local calendar day (avoids UTC shift from bare ISO date strings). */
function parseYmdToLocalDate(ymd: string): Date | null {
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(ymd.trim());
  if (!m) return null;
  const y = Number(m[1]);
  const mo = Number(m[2]) - 1;
  const d = Number(m[3]);
  const date = new Date(y, mo, d);
  if (
    date.getFullYear() !== y ||
    date.getMonth() !== mo ||
    date.getDate() !== d
  ) {
    return null;
  }
  return startOfLocalDay(date);
}

/** Not yet shelf-listed: still pending or receiving (completed POs skip ETA reminder). */
function isNotYetListedOnShelf(row: PoWorkbenchListRow): boolean {
  return row.status === "pending" || row.status === "receiving";
}

/** ETA vs today (local calendar days) for unlisted POs; labels from poWorkbench i18n. */
function buildEtaVarianceReminder(
  row: PoWorkbenchListRow,
  t: (key: string, options?: Record<string, unknown>) => string,
): EtaVarianceReminder | null {
  if (!isNotYetListedOnShelf(row)) return null;

  const etaYmd = formatDateYmd(row.estimatedArrivalDate);
  if (!etaYmd) return null;

  const etaDay = parseYmdToLocalDate(etaYmd);
  if (!etaDay) return null;

  const today = startOfLocalDay(new Date());
  const diffDays = Math.round((today.getTime() - etaDay.getTime()) / 86400000);
  if (diffDays === 0) return null;

  if (diffDays > 0) {
    return {
      color: "warning",
      label: t("detailsHeader.etaUnlistedAfterEta", { days: diffDays }),
    };
  }

  return {
    color: "primary",
    label: t("detailsHeader.etaUnlistedBeforeEta", {
      days: Math.abs(diffDays),
    }),
  };
}

/** Renders receive and escalation chips. ETA vs today only when `showEtaVsTodayChip` (e.g. details header, not list). */
function WorkbenchResultStatusChips({
  row,
  showEtaVsTodayChip = false,
}: {
  row: PoWorkbenchListRow;
  showEtaVsTodayChip?: boolean;
}) {
  const { t } = useTranslation("poWorkbench");
  const { t: tPo } = useTranslation("purchaseOrder");
  const theme = useTheme();
  const chipSx = {
    ...ETA_VARIANCE_CHIP_SX,
    fontSize: theme.typography.body2.fontSize,
  };
  const etaVarianceReminder = showEtaVsTodayChip
    ? buildEtaVarianceReminder(row, t)
    : null;

  return (
    <Stack
      direction="row"
      spacing={0.5}
      flexWrap="wrap"
      useFlexGap
      justifyContent="flex-end"
      alignItems="center"
      sx={{ flexShrink: 0 }}
    >
      {etaVarianceReminder ? (
        <Chip
          size="small"
          variant="outlined"
          color={etaVarianceReminder.color}
          label={etaVarianceReminder.label}
          sx={chipSx}
        />
      ) : null}
      <PoWorkbenchReceiveStatusChip status={row.status} />
      {row.escalated ? (
        <Chip
          size="small"
          variant="outlined"
          color="warning"
          label={tPo("escalated")}
          sx={chipSx}
        />
      ) : null}
    </Stack>
  );
}

function WorkbenchPoSupplierHeader({ row }: PoSupplierBlockProps) {
  return (
    <Stack spacing={0.5} sx={{ minWidth: 0, flex: 1, overflow: "hidden" }}>
      <Typography
        variant="body1"
        color="text.primary"
        fontWeight={600}
        title={row.poNumber}
        sx={HEADER_LINE_CLAMP_SX}
      >
        {row.poNumber}
      </Typography>
      <Typography
        variant="body2"
        color="text.secondary"
        title={row.supplierName}
        sx={HEADER_LINE_CLAMP_SX}
      >
        {row.supplierName}
      </Typography>
    </Stack>
  );
}

function WorkbenchResultSummaryHeader({ row }: { row: PoWorkbenchListRow }) {
  const theme = useTheme();
  const narrowHeader = useMediaQuery(theme.breakpoints.down("sm"), {
    noSsr: true,
  });

  const headerDateRow = (
    <Stack
      {...DATE_ROW_SX}
      useFlexGap
      justifyContent="flex-end"
      sx={{ width: "100%" }}
    >
      <WorkbenchResultDateSegment
        kind="order"
        dateYmd={formatDateYmd(row.orderDate)}
      />
      <WorkbenchResultDateSegment
        kind="eta"
        dateYmd={formatDateYmd(row.estimatedArrivalDate)}
      />
    </Stack>
  );

  const statusRow = (
    <Stack direction="row" justifyContent="flex-end" sx={{ width: "100%" }}>
      <WorkbenchResultStatusChips row={row} showEtaVsTodayChip />
    </Stack>
  );

  if (narrowHeader) {
    return (
      <Stack
        direction="column"
        spacing={1.5}
        sx={{ minWidth: 0, width: "100%" }}
      >
        <WorkbenchPoSupplierHeader row={row} />
        {statusRow}
        {headerDateRow}
      </Stack>
    );
  }

  return (
    <Stack
      direction="row"
      justifyContent="space-between"
      alignItems="flex-start"
      spacing={2}
      sx={{ minWidth: 0, width: "100%" }}
    >
      <WorkbenchPoSupplierHeader row={row} />
      <Stack
        direction="column"
        spacing={1}
        alignItems="flex-end"
        sx={{ flexShrink: 0, minWidth: 0, maxWidth: "100%" }}
      >
        {statusRow}
        {headerDateRow}
      </Stack>
    </Stack>
  );
}

export default function PoWorkbenchResultSummary({
  row,
  layout = "list",
}: PoWorkbenchResultSummaryProps) {
  if (layout === "header") {
    return <WorkbenchResultSummaryHeader row={row} />;
  }

  const listDateRow = (
    <Stack {...DATE_ROW_SX} sx={{ pt: 0.25 }}>
      <WorkbenchResultDateSegment
        kind="order"
        dateYmd={formatDateYmd(row.orderDate)}
      />
      <WorkbenchResultDateSegment
        kind="eta"
        dateYmd={formatDateYmd(row.estimatedArrivalDate)}
      />
    </Stack>
  );

  return (
    <Stack spacing={0.25} sx={{ minWidth: 0, width: "100%" }}>
      <Stack spacing={0.25} sx={{ minWidth: 0, width: "100%" }}>
        <Stack
          direction="row"
          alignItems="center"
          justifyContent="space-between"
          spacing={1}
          sx={{ minWidth: 0 }}
        >
          <Typography
            variant="body1"
            color="text.primary"
            fontWeight={600}
            sx={PO_WORKBENCH_RESULT_LINE_SX}
          >
            {row.poNumber}
          </Typography>
          <WorkbenchResultStatusChips row={row} />
        </Stack>
        <Typography variant="body2" color="text.secondary" sx={PO_WORKBENCH_RESULT_LINE_SX}>
          {row.supplierName}
        </Typography>
      </Stack>
      {listDateRow}
    </Stack>
  );
}
