"use client";

import React, { useState } from "react";
import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  Box,
  Chip,
  Stack,
  TableContainer,
  Typography,
} from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import Inventory2Icon from "@mui/icons-material/Inventory2";
import { useTranslation } from "react-i18next";
import { ItemLotTraceLocationBlock } from "@/app/api/itemTracing";
import type { WarehouseFocusRequest } from "./ItemTracing";
import { blockWarehouseCode } from "./buildLocationBlockGraphNodes";
import { createTraceLabelTranslator } from "./traceLabelUtils";
import {
  resolveStockTakeAcceptedQty,
  resolveStockTakeBookQty,
} from "./traceStockTakeUtils";
import {
  FilterableDataTable,
  type FilterableColumnDef,
} from "./itemTracingTableFilters";

interface Props {
  locationBlocks: ItemLotTraceLocationBlock[];
  onFocusWarehouse?: (request: WarehouseFocusRequest) => void;
}

/** Compact sub-table for sections that may have many rows. */
function SectionTable<T>({
  title,
  rows,
  columns,
  getRowKey,
}: {
  title: string;
  rows: T[];
  columns: FilterableColumnDef<T>[];
  getRowKey: (row: T, index: number) => string;
}) {
  const { t } = useTranslation("itemTracing");
  const [showAll, setShowAll] = useState(false);

  return (
    <Box>
      <Typography variant="subtitle2" gutterBottom>
        {title} ({rows.length})
      </Typography>
      <TableContainer>
        <FilterableDataTable
          rows={rows}
          columns={columns}
          getRowKey={getRowKey}
          emptyLabel={t("noRecords")}
          collapseAfter={10}
          showAll={showAll}
          onToggleShowAll={() => setShowAll((v) => !v)}
          showAllLabel={(count) => t("locationsShowAll", { count })}
          collapseLabel={(count) => t("locationsCollapse", { count })}
        />
      </TableContainer>
    </Box>
  );
}


/** FP-MTMS Version Checklist | Functions Ref. No. 13 | v1.0.0 | 2026-07-17 */
const ItemTracingLocations: React.FC<Props> = ({
  locationBlocks,
  onFocusWarehouse,
}) => {
  const { t } = useTranslation("itemTracing");
  const tr = createTraceLabelTranslator(t);

  if (!locationBlocks || locationBlocks.length === 0) return null;

  return (
    <Stack spacing={1.5}>
      <Stack direction="row" alignItems="center" spacing={1}>
        <Inventory2Icon fontSize="small" color="primary" />
        <Typography variant="subtitle1" fontWeight={600}>
          {t("locationHeader", { count: locationBlocks.length })}
        </Typography>
        <Chip
          label={`${locationBlocks.length}`}
          size="small"
          color="primary"
          variant="outlined"
        />
      </Stack>

      {locationBlocks.map((block) => {
        const totalIn = block.warehouseLines.reduce(
          (s, l) => s + (l.inQty || 0),
          0,
        );
        const totalOut = block.warehouseLines.reduce(
          (s, l) => s + (l.outQty || 0),
          0,
        );
        const available = totalIn - totalOut;
        const lastMovement = block.movements[0];
        const stockTakeVariance = block.stockTakeEvents.reduce(
          (s, st) => s + (st.varianceQty || 0),
          0,
        );

        return (
          <Accordion
            key={block.inventoryLotId}
            slotProps={{ transition: { unmountOnExit: true } }}
          >
            <AccordionSummary expandIcon={<ExpandMoreIcon />}>
              <Stack
                direction="row"
                alignItems="center"
                spacing={1.5}
                flexWrap="wrap"
                sx={{ width: "100%", gap: 0.5 }}
              >
                <Typography variant="body2" fontWeight={600}>
                  {block.warehouseLines
                    .map((l) => l.warehouseCode)
                    .filter(Boolean)
                    .join(" / ") || `Lot #${block.inventoryLotId}`}
                </Typography>
                {block.itemName && (
                  <Typography variant="caption" color="text.secondary">
                    {block.itemCode} ??{block.itemName}
                  </Typography>
                )}
                <Chip
                  label={`${t("available")}: ${available}`}
                  size="small"
                  color={available > 0 ? "success" : "default"}
                  variant="outlined"
                />
                <Typography variant="caption" color="text.secondary">
                  {t("inQty")}: {totalIn} / {t("outQty")}: {totalOut}
                </Typography>
                {block.movements.length > 0 && (
                  <Chip
                    label={`${block.movements.length} moves`}
                    size="small"
                    variant="outlined"
                  />
                )}
                {lastMovement?.timestamp && (
                  <Typography variant="caption" color="text.secondary">
                    {t("lastMove")}: {lastMovement.timestamp}
                  </Typography>
                )}
                {stockTakeVariance !== 0 && (
                  <Chip
                    label={`? ${stockTakeVariance}`}
                    size="small"
                    color={stockTakeVariance !== 0 ? "warning" : "default"}
                    variant="outlined"
                  />
                )}
                {onFocusWarehouse ? (
                  <Chip
                    label={t("focusWarehouseInGraph")}
                    size="small"
                    color="primary"
                    variant="filled"
                    clickable
                    onClick={(e) => {
                      e.stopPropagation();
                      onFocusWarehouse({
                        inventoryLotId: block.inventoryLotId,
                        warehouseCode: blockWarehouseCode(block),
                      });
                    }}
                    sx={{ ml: "auto" }}
                  />
                ) : null}
              </Stack>
            </AccordionSummary>

            <AccordionDetails>
              <Stack spacing={2}>
                {block.warehouseLines.length > 0 && (
                  <SectionTable
                    title={t("warehouseLines")}
                    rows={block.warehouseLines}
                    getRowKey={(wl) => String(wl.inventoryLotLineId)}
                    columns={[
                      {
                        key: "warehouse",
                        label: t("warehouse"),
                        value: (wl) => wl.warehouseCode,
                      },
                      {
                        key: "inQty",
                        label: t("inQty"),
                        align: "right",
                        value: (wl) => wl.inQty,
                      },
                      {
                        key: "outQty",
                        label: t("outQty"),
                        align: "right",
                        value: (wl) => wl.outQty,
                      },
                      {
                        key: "available",
                        label: t("available"),
                        align: "right",
                        value: (wl) => wl.availableQty,
                      },
                      {
                        key: "status",
                        label: t("status"),
                        value: (wl) => tr.lotLineStatus(wl.status),
                      },
                    ]}
                  />
                )}

                {block.origins.length > 0 && (
                  <SectionTable
                    title={t("origins")}
                    rows={block.origins}
                    getRowKey={(o) => String(o.stockInLineId)}
                    columns={[
                      {
                        key: "type",
                        label: t("type"),
                        value: (o) => o.type,
                        cell: (o) => (
                          <Chip
                            label={o.type}
                            size="small"
                            variant="outlined"
                          />
                        ),
                      },
                      {
                        key: "refCode",
                        label: t("refCode"),
                        value: (o) => o.refCode,
                      },
                      {
                        key: "supplier",
                        label: t("supplier"),
                        value: (o) => o.supplierName || o.supplierCode,
                      },
                      {
                        key: "qty",
                        label: t("qty"),
                        align: "right",
                        value: (o) => o.acceptedQty,
                      },
                      {
                        key: "date",
                        label: t("date"),
                        value: (o) => o.receiptDate,
                      },
                    ]}
                  />
                )}

                {block.qcResults.length > 0 && (
                  <SectionTable
                    title={t("tabQc")}
                    rows={block.qcResults}
                    getRowKey={(qc) => `${qc.stockInLineId}-${qc.created}`}
                    columns={[
                      {
                        key: "qcPassed",
                        label: t("qcPassed"),
                        value: (qc) =>
                          qc.qcPassed ? t("qcPassed") : t("qcFailed"),
                        cell: (qc) => (
                          <Chip
                            label={qc.qcPassed ? t("qcPassed") : t("qcFailed")}
                            size="small"
                            color={qc.qcPassed ? "success" : "error"}
                            variant="outlined"
                          />
                        ),
                      },
                      {
                        key: "acceptedQty",
                        label: t("acceptedQty"),
                        align: "right",
                        value: (qc) => qc.acceptedQty,
                      },
                      {
                        key: "failQty",
                        label: t("failQty"),
                        align: "right",
                        value: (qc) => qc.failQty,
                      },
                      {
                        key: "qcType",
                        label: t("detailQcType"),
                        value: (qc) => qc.qcType,
                      },
                      {
                        key: "handler",
                        label: t("handler"),
                        value: (qc) => qc.handledBy,
                      },
                      {
                        key: "date",
                        label: t("date"),
                        value: (qc) => qc.created,
                      },
                    ]}
                  />
                )}

                {block.purchaseEvents && block.purchaseEvents.length > 0 && (
                  <SectionTable
                    title={t("categoryPurchase")}
                    rows={block.purchaseEvents}
                    getRowKey={(pe) => String(pe.purchaseOrderLineId)}
                    columns={[
                      {
                        key: "po",
                        label: t("detailPurchaseOrderNo"),
                        value: (pe) => pe.purchaseOrderCode,
                      },
                      {
                        key: "supplier",
                        label: t("supplier"),
                        value: (pe) => pe.supplierName || pe.supplierCode,
                      },
                      {
                        key: "orderQty",
                        label: t("detailOrderQty"),
                        align: "right",
                        value: (pe) => pe.orderQty,
                      },
                      {
                        key: "putAwayQty",
                        label: t("detailPutAwayQty"),
                        align: "right",
                        value: (pe) => pe.putAwayQty,
                      },
                      {
                        key: "date",
                        label: t("date"),
                        value: (pe) => pe.orderDate,
                      },
                    ]}
                  />
                )}

                {block.putawayEvents.length > 0 && (
                  <SectionTable
                    title={t("nodePutaway")}
                    rows={block.putawayEvents}
                    getRowKey={(pa, idx) => `${pa.inventoryLotLineId}-${idx}`}
                    columns={[
                      {
                        key: "warehouse",
                        label: t("warehouse"),
                        value: (pa) => pa.warehouseCode,
                      },
                      {
                        key: "qty",
                        label: t("qty"),
                        align: "right",
                        value: (pa) => pa.qty,
                      },
                      {
                        key: "handler",
                        label: t("handler"),
                        value: (pa) => pa.handledBy,
                      },
                      {
                        key: "refCode",
                        label: t("refCode"),
                        value: (pa) => pa.refCode,
                      },
                      {
                        key: "date",
                        label: t("date"),
                        value: (pa) => pa.timestamp,
                      },
                    ]}
                  />
                )}

                {block.movements.length > 0 && (
                  <SectionTable
                    title={t("movements")}
                    rows={block.movements}
                    getRowKey={(m, idx) => `${m.refCode}-${m.timestamp}-${idx}`}
                    columns={[
                      {
                        key: "direction",
                        label: t("direction"),
                        value: (m) => m.direction,
                        cell: (m) => (
                          <Chip
                            label={m.direction}
                            size="small"
                            color={m.direction === "IN" ? "success" : "error"}
                            variant="outlined"
                          />
                        ),
                      },
                      {
                        key: "type",
                        label: t("type"),
                        value: (m) => m.refType,
                      },
                      {
                        key: "refCode",
                        label: t("refCode"),
                        value: (m) => m.refCode,
                      },
                      {
                        key: "qty",
                        label: t("qty"),
                        align: "right",
                        value: (m) => m.qty,
                      },
                      {
                        key: "warehouse",
                        label: t("warehouse"),
                        value: (m) => m.warehouseCode,
                      },
                      {
                        key: "date",
                        label: t("date"),
                        value: (m) => m.timestamp,
                      },
                    ]}
                  />
                )}

                {block.outboundUsage.length > 0 && (
                  <SectionTable
                    title={t("outbound")}
                    rows={block.outboundUsage}
                    getRowKey={(o, idx) => `${o.stockOutLineId}-${idx}`}
                    columns={[
                      {
                        key: "pickOrder",
                        label: t("pickOrder"),
                        value: (o) => o.pickOrderCode || o.deliveryOrderCode,
                      },
                      {
                        key: "type",
                        label: t("type"),
                        value: (o) => tr.usageType(o.usageType),
                        cell: (o) => (
                          <Chip
                            label={tr.usageType(o.usageType)}
                            size="small"
                            variant="outlined"
                          />
                        ),
                      },
                      {
                        key: "qty",
                        label: t("qty"),
                        align: "right",
                        value: (o) => o.qty,
                      },
                      {
                        key: "handler",
                        label: t("handler"),
                        value: (o) => o.handler,
                      },
                      {
                        key: "date",
                        label: t("date"),
                        value: (o) => o.timestamp,
                      },
                    ]}
                  />
                )}

                {block.stockTakeEvents.length > 0 && (
                  <SectionTable
                    title={t("stockTake")}
                    rows={block.stockTakeEvents}
                    getRowKey={(st, idx) => `${st.stockTakeCode}-${idx}`}
                    columns={[
                      {
                        key: "code",
                        label: t("stockTakeCode"),
                        value: (st) => st.stockTakeCode,
                      },
                      {
                        key: "section",
                        label: t("section"),
                        value: (st) => st.stockTakeSection,
                      },
                      {
                        key: "round",
                        label: t("round"),
                        value: (st) => st.stockTakeRoundName,
                      },
                      {
                        key: "before",
                        label: t("before"),
                        align: "right",
                        value: (st) =>
                          resolveStockTakeBookQty(st.recordDetail, st.beforeQty),
                      },
                      {
                        key: "after",
                        label: t("after"),
                        align: "right",
                        value: (st) =>
                          resolveStockTakeAcceptedQty(
                            st.recordDetail,
                            st.afterQty,
                          ),
                      },
                      {
                        key: "variance",
                        label: t("variance"),
                        align: "right",
                        value: (st) =>
                          st.recordDetail?.varianceQty != null
                            ? st.recordDetail.varianceQty
                            : st.varianceQty,
                      },
                      {
                        key: "date",
                        label: t("date"),
                        value: (st) => st.timestamp,
                      },
                    ]}
                  />
                )}

                {block.adjustments.length > 0 && (
                  <SectionTable
                    title={t("tabAdjustments")}
                    rows={block.adjustments}
                    getRowKey={(adj, idx) =>
                      `${adj.refCode}-${adj.timestamp}-${idx}`
                    }
                    columns={[
                      {
                        key: "type",
                        label: t("type"),
                        value: (adj) => adj.adjustmentType,
                      },
                      {
                        key: "direction",
                        label: t("direction"),
                        value: (adj) => adj.direction,
                        cell: (adj) => (
                          <Chip
                            label={adj.direction}
                            size="small"
                            color={adj.direction === "IN" ? "success" : "error"}
                            variant="outlined"
                          />
                        ),
                      },
                      {
                        key: "qty",
                        label: t("qty"),
                        align: "right",
                        value: (adj) => adj.qty,
                      },
                      {
                        key: "remarks",
                        label: t("remarks"),
                        value: (adj) => adj.reason,
                      },
                      {
                        key: "handler",
                        label: t("handler"),
                        value: (adj) => adj.handledBy,
                      },
                      {
                        key: "date",
                        label: t("date"),
                        value: (adj) => adj.timestamp,
                      },
                    ]}
                  />
                )}

                {block.transfers.length > 0 && (
                  <SectionTable
                    title={t("tabTransfers")}
                    rows={block.transfers}
                    getRowKey={(xfer, idx) => `${xfer.transferCode}-${idx}`}
                    columns={[
                      {
                        key: "from",
                        label: t("from"),
                        value: (xfer) => xfer.fromWarehouse,
                      },
                      {
                        key: "to",
                        label: t("to"),
                        value: (xfer) => xfer.toWarehouse,
                      },
                      {
                        key: "qty",
                        label: t("qty"),
                        align: "right",
                        value: (xfer) => xfer.qty,
                      },
                      {
                        key: "refCode",
                        label: t("refCode"),
                        value: (xfer) => xfer.transferCode,
                      },
                      {
                        key: "date",
                        label: t("date"),
                        value: (xfer) => xfer.timestamp,
                      },
                    ]}
                  />
                )}

                {block.doDeliveries.length > 0 && (
                  <SectionTable
                    title={t("deliveryOrder")}
                    rows={block.doDeliveries}
                    getRowKey={(dd, idx) => `${dd.stockOutLineId}-${idx}`}
                    columns={[
                      {
                        key: "pickOrder",
                        label: t("pickOrder"),
                        value: (dd) => dd.pickOrderCode,
                      },
                      {
                        key: "deliveryOrder",
                        label: t("deliveryOrder"),
                        value: (dd) => dd.deliveryOrderCode,
                      },
                      {
                        key: "deliveryNoteCode",
                        label: t("deliveryNoteCode"),
                        value: (dd) => dd.deliveryNoteCode || "—",
                      },
                      {
                        key: "ticketNo",
                        label: t("ticketNo"),
                        value: (dd) => dd.ticketNo || "—",
                      },
                      {
                        key: "qty",
                        label: t("qty"),
                        align: "right",
                        value: (dd) => dd.qty,
                      },
                      {
                        key: "handler",
                        label: t("handler"),
                        value: (dd) => dd.handler,
                      },
                      {
                        key: "date",
                        label: t("date"),
                        value: (dd) => dd.timestamp,
                      },
                    ]}
                  />
                )}

                {block.failEvents.length > 0 && (
                  <SectionTable
                    title={t("nodeFail")}
                    rows={block.failEvents}
                    getRowKey={(fe) => String(fe.failId)}
                    columns={[
                      {
                        key: "category",
                        label: t("detailFailCategory"),
                        value: (fe) => `${fe.failType} / ${fe.category}`,
                      },
                      {
                        key: "qty",
                        label: t("qty"),
                        align: "right",
                        value: (fe) => fe.qty,
                      },
                      {
                        key: "pickOrder",
                        label: t("pickOrder"),
                        value: (fe) => fe.pickOrderCode,
                      },
                      {
                        key: "handler",
                        label: t("handler"),
                        value: (fe) => fe.handlerName,
                      },
                      {
                        key: "date",
                        label: t("date"),
                        value: (fe) => fe.recordDate,
                      },
                    ]}
                  />
                )}

                {block.returnEvents.length > 0 && (
                  <SectionTable
                    title={t("nodeReturn")}
                    rows={block.returnEvents}
                    getRowKey={(re, idx) => `${re.stockOutLineId}-${idx}`}
                    columns={[
                      {
                        key: "type",
                        label: t("type"),
                        value: (re) => re.movementType,
                      },
                      {
                        key: "qty",
                        label: t("qty"),
                        align: "right",
                        value: (re) => re.qty,
                      },
                      {
                        key: "warehouse",
                        label: t("warehouse"),
                        value: (re) => re.warehouseCode,
                      },
                      {
                        key: "remarks",
                        label: t("remarks"),
                        value: (re) => re.remarks,
                      },
                      {
                        key: "date",
                        label: t("date"),
                        value: (re) => re.timestamp,
                      },
                    ]}
                  />
                )}

                {block.openMovements.length > 0 && (
                  <SectionTable
                    title={t("nodeOpen")}
                    rows={block.openMovements}
                    getRowKey={(om) => String(om.stockInLineId)}
                    columns={[
                      {
                        key: "warehouse",
                        label: t("warehouse"),
                        value: (om) => om.warehouseCode,
                      },
                      {
                        key: "qty",
                        label: t("qty"),
                        align: "right",
                        value: (om) => om.qty,
                      },
                      {
                        key: "refCode",
                        label: t("refCode"),
                        value: (om) => om.refCode,
                      },
                      {
                        key: "handler",
                        label: t("handler"),
                        value: (om) => om.handledBy,
                      },
                      {
                        key: "date",
                        label: t("date"),
                        value: (om) => om.timestamp,
                      },
                    ]}
                  />
                )}
              </Stack>
            </AccordionDetails>
          </Accordion>
        );
      })}
    </Stack>
  );
};

export default ItemTracingLocations;
