"use client";

import {
  Box,
  Button,
  Chip,
  Grid,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  Typography,
} from "@mui/material";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { ItemLotTraceResponse } from "@/app/api/itemTracing";
import ItemTracingDocLink from "./ItemTracingDocLink";
import { createTraceLabelTranslator } from "./traceLabelUtils";
import { formatQty } from "./traceQtyUtils";
import type { WarehouseFocusRequest } from "./ItemTracing";

type Props = {
  data: ItemLotTraceResponse;
  onFocusWarehouse?: (request: WarehouseFocusRequest) => void;
  onExportExcel?: () => void;
};

type SummaryWarehouseRow = {
  key: string;
  inventoryLotId: number;
  warehouseCode: string;
  inQty: number;
  outQty: number;
  availableQty: number;
  status: string;
};

/** FP-MTMS Version Checklist | Functions Ref. No. 13 | v1.0.0 | 2026-07-17 */
const ItemTracingSummary: React.FC<Props> = ({
  data,
  onFocusWarehouse,
  onExportExcel,
}) => {
  const { t } = useTranslation("itemTracing");
  const tr = useMemo(() => createTraceLabelTranslator(t), [t]);
  const { lot, warehouseLines, joPrelude, alternateLocations, locationBlocks } =
    data;

  const combinedWarehouseRows = useMemo((): SummaryWarehouseRow[] => {
    const primary = warehouseLines.map((w) => ({
      key: `primary-${w.inventoryLotLineId}`,
      inventoryLotId: lot.inventoryLotId,
      warehouseCode: w.warehouseCode,
      inQty: w.inQty,
      outQty: w.outQty,
      availableQty: w.availableQty,
      status: w.status,
    }));

    const fromBlocks = (locationBlocks ?? []).flatMap((block) =>
      block.warehouseLines.map((w) => ({
        key: `alt-${block.inventoryLotId}-${w.inventoryLotLineId}`,
        inventoryLotId: block.inventoryLotId,
        warehouseCode: w.warehouseCode,
        inQty: w.inQty,
        outQty: w.outQty,
        availableQty: w.availableQty,
        status: w.status,
      })),
    );

    if (fromBlocks.length > 0) {
      return [...primary, ...fromBlocks];
    }

    // Fallback when location blocks are absent but alternateLocations exist.
    const fromAlts = alternateLocations.map((loc) => ({
      key: `alt-loc-${loc.inventoryLotId}-${loc.inventoryLotLineId}`,
      inventoryLotId: loc.inventoryLotId,
      warehouseCode: loc.warehouseCode,
      inQty: 0,
      outQty: 0,
      availableQty: loc.availableQty,
      status: "",
    }));
    return [...primary, ...fromAlts];
  }, [
    warehouseLines,
    locationBlocks,
    alternateLocations,
    lot.inventoryLotId,
  ]);

  const totalAvailable = combinedWarehouseRows.reduce(
    (s, w) => s + (w.availableQty ?? 0),
    0,
  );

  return (
    <Paper variant="outlined" sx={{ p: 2.5 }}>
      <Stack
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        spacing={1}
      >
        <Typography variant="overline" color="text.secondary">
          {t("summary")}
        </Typography>
        {onExportExcel && (
          <Button
            size="small"
            variant="outlined"
            onClick={onExportExcel}
            title={t("exportExcelTooltip")}
          >
            {t("exportExcel")}
          </Button>
        )}
      </Stack>
      <Stack
        direction={{ xs: "column", md: "row" }}
        spacing={2}
        alignItems={{ md: "center" }}
        sx={{ mt: 1 }}
      >
        <Box sx={{ flex: 1 }}>
          <Typography variant="h5" fontWeight={700}>
            {lot.lotNo || "—"}
          </Typography>
          <Typography variant="subtitle1" color="text.secondary">
            {lot.itemCode} · {lot.itemName}
          </Typography>
        </Box>
        <Chip
          label={`${t("totalAvailable")}: ${formatQty(
            totalAvailable,
            lot.uom,
          )}`}
          color="primary"
          variant="outlined"
        />
      </Stack>
      <Grid container spacing={2} sx={{ mt: 2 }}>
        <Grid item xs={6} sm={3}>
          <Typography variant="caption" color="text.secondary">
            {t("expiryDate")}
          </Typography>
          <Typography variant="body2">{lot.expiryDate ?? "—"}</Typography>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Typography variant="caption" color="text.secondary">
            {t("productionDate")}
          </Typography>
          <Typography variant="body2">{lot.productionDate ?? "—"}</Typography>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Typography variant="caption" color="text.secondary">
            {t("stockInDate")}
          </Typography>
          <Typography variant="body2">{lot.stockInDate ?? "—"}</Typography>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Typography variant="caption" color="text.secondary">
            {t("uom")}
          </Typography>
          <Typography variant="body2">{lot.uom || "—"}</Typography>
        </Grid>
      </Grid>
      {joPrelude && (
        <Box sx={{ mt: 2, p: 1.5, bgcolor: "action.hover", borderRadius: 1 }}>
          <Typography variant="subtitle2" gutterBottom>
            {t("joContext")}
          </Typography>
          <Grid container spacing={1}>
            <Grid item xs={6} sm={3}>
              <Typography variant="caption" color="text.secondary">
                {t("jobOrder")}
              </Typography>
              <Typography variant="body2">
                {joPrelude.jobOrder.jobOrderId != null ? (
                  <ItemTracingDocLink
                    kind="jo"
                    id={joPrelude.jobOrder.jobOrderId}
                    code={joPrelude.jobOrder.jobOrderCode}
                  />
                ) : (
                  joPrelude.jobOrder.jobOrderCode || "—"
                )}
              </Typography>
            </Grid>
            <Grid item xs={6} sm={3}>
              <Typography variant="caption" color="text.secondary">
                {t("status")}
              </Typography>
              <Typography variant="body2">
                {tr.joStatus(joPrelude.jobOrder.status)}
              </Typography>
            </Grid>
            <Grid item xs={6} sm={3}>
              <Typography variant="caption" color="text.secondary">
                {t("planStart")}
              </Typography>
              <Typography variant="body2">
                {joPrelude.jobOrder.planStart ?? "—"}
              </Typography>
            </Grid>
            <Grid item xs={6} sm={3}>
              <Typography variant="caption" color="text.secondary">
                {t("plannedQty")}
              </Typography>
              <Typography variant="body2">
                {formatQty(Number(joPrelude.jobOrder.reqQty), lot.uom)}
              </Typography>
            </Grid>
          </Grid>
        </Box>
      )}
      {combinedWarehouseRows.length > 0 && (
        <Box sx={{ mt: 3 }}>
          <Table size="small" sx={{ tableLayout: "auto" }}>
            <TableHead>
              <TableRow>
                <TableCell>{t("warehouse")}</TableCell>
                <TableCell align="right">{t("inQty")}</TableCell>
                <TableCell align="right">{t("outQty")}</TableCell>
                <TableCell align="right">{t("available")}</TableCell>
                <TableCell>{t("status")}</TableCell>
                {onFocusWarehouse && (
                  <TableCell align="right">{t("action")}</TableCell>
                )}
              </TableRow>
            </TableHead>
            <TableBody>
              {combinedWarehouseRows.map((w) => (
                <TableRow key={w.key}>
                  <TableCell>{w.warehouseCode || "—"}</TableCell>
                  <TableCell align="right">
                    {formatQty(w.inQty, lot.uom)}
                  </TableCell>
                  <TableCell align="right">
                    {formatQty(w.outQty, lot.uom)}
                  </TableCell>
                  <TableCell align="right">
                    {formatQty(w.availableQty, lot.uom)}
                  </TableCell>
                  <TableCell>
                    {w.status ? (
                      <Chip
                        size="small"
                        label={tr.lotLineStatus(w.status)}
                        variant="outlined"
                      />
                    ) : (
                      "—"
                    )}
                  </TableCell>
                  {onFocusWarehouse && (
                    <TableCell align="right">
                      {w.warehouseCode?.trim() ? (
                        <Button
                          size="small"
                          variant="outlined"
                          onClick={() =>
                            onFocusWarehouse({
                              inventoryLotId: w.inventoryLotId,
                              warehouseCode: w.warehouseCode,
                            })
                          }
                        >
                          {t("focusWarehouseInGraph")}
                        </Button>
                      ) : (
                        "—"
                      )}
                    </TableCell>
                  )}
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Box>
      )}
    </Paper>
  );
};

export default ItemTracingSummary;
