"use client";

import {
  Box,
  Chip,
  Divider,
  IconButton,
  List,
  ListItem,
  ListItemText,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableRow,
  Typography,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { useTranslation } from "react-i18next";
import { TraceGraphNode } from "./buildTraceGraphNodes";
import ItemTracingDocLink from "./ItemTracingDocLink";
import ItemTracingLotTraceLink from "./ItemTracingLotTraceLink";
import ItemTracingStockTakeLifecycle from "./ItemTracingStockTakeLifecycle";
import { formatQty } from "./traceQtyUtils";
import { buildStockTakeLifecycleStages } from "./traceStockTakeUtils";

type Props = {
  node: TraceGraphNode;
  onClose?: () => void;
};

/** FP-MTMS Version Checklist | Functions Ref. No. 15 | v1.0.1 | 2026-07-20 */
const ItemTracingNodeDetailPanel: React.FC<Props> = ({ node, onClose }) => {
  const { t } = useTranslation("itemTracing");

  const hasDocLink = node.docLinkKind && node.refCode;
  const lifecycleStages =
    node.kind === "STOCK_TAKE" && node.stockTakeRecordDetail
      ? buildStockTakeLifecycleStages(node.stockTakeRecordDetail)
      : [];
  const activeStageCount = lifecycleStages.filter((s) => s.isActive).length;

  return (
    <Paper
      elevation={0}
      square
      sx={{
        width: "100%",
        height: "100%",
        display: "flex",
        flexDirection: "column",
        bgcolor: "background.paper",
        borderRight: 1,
        borderColor: "divider",
        overflow: "hidden",
      }}
    >
      <Box
        sx={{
          px: 1.5,
          py: 1.25,
          borderBottom: 1,
          borderColor: "divider",
          flexShrink: 0,
        }}
      >
        <Stack direction="row" spacing={0.5} alignItems="flex-start" justifyContent="space-between">
          <Stack spacing={0.5} sx={{ minWidth: 0, flex: 1 }}>
            <Typography variant="subtitle2" fontWeight={700}>
              {t("nodeDetailTitle")}
            </Typography>
            {node.categoryLabel && (
              <Chip size="small" label={node.categoryLabel} color="primary" variant="outlined" />
            )}
          </Stack>
          {onClose && (
            <IconButton size="small" onClick={onClose} aria-label={t("nodeDetailClose")} sx={{ mt: -0.5 }}>
              <CloseIcon fontSize="small" />
            </IconButton>
          )}
        </Stack>
      </Box>

      <Box sx={{ flex: 1, overflow: "auto", px: 1.5, py: 1.25 }}>
        <Typography variant="subtitle2" fontWeight={600} gutterBottom>
          {hasDocLink ? (
            <ItemTracingDocLink
              kind={node.docLinkKind!}
              code={node.refCode!}
              id={node.refId}
              consoCode={node.consoCode ?? node.refCode}
              ticketNo={node.docLinkTicketNo}
              targetDate={node.docLinkTargetDate}
              openInNewTab
            />
          ) : (
            node.title
          )}
        </Typography>
        {node.subtitle && (
          <Typography variant="caption" color="text.secondary" display="block" gutterBottom>
            {node.subtitle}
          </Typography>
        )}

        <Table size="small" sx={{ mt: 0.5 }}>
          <TableBody>
            {node.details.map((row, i) => (
              <TableRow key={`${row.label}-${i}`}>
                <TableCell
                  component="th"
                  scope="row"
                  sx={{
                    width: "42%",
                    fontWeight: 600,
                    color: "text.secondary",
                    border: 0,
                    py: 0.5,
                    pl: 0,
                    fontSize: "0.75rem",
                    verticalAlign: "top",
                  }}
                >
                  {row.label}
                </TableCell>
                <TableCell
                  sx={{
                    border: 0,
                    py: 0.5,
                    pr: 0,
                    fontSize: "0.8125rem",
                    whiteSpace: "pre-line",
                    verticalAlign: "top",
                  }}
                >
                  {row.variant === "qcCriteriaList" && row.qcCriteriaItems?.length ? (
                    <List dense disablePadding sx={{ width: "100%" }}>
                      {row.qcCriteriaItems.map((item, idx) => (
                        <ListItem
                          key={`${item.name}-${idx}`}
                          disableGutters
                          alignItems="flex-start"
                          sx={{
                            py: 0.5,
                            borderBottom:
                              idx < row.qcCriteriaItems!.length - 1 ? "1px solid" : "none",
                            borderColor: "divider",
                          }}
                        >
                          <ListItemText
                            primary={
                              <Stack
                                direction="row"
                                spacing={0.5}
                                alignItems="center"
                                flexWrap="wrap"
                                useFlexGap
                              >
                                <Typography variant="caption" fontWeight={600} component="span">
                                  {item.name}
                                </Typography>
                                <Chip
                                  size="small"
                                  label={item.passed ? t("qcPassed") : t("qcFailed")}
                                  color={item.passed ? "success" : "error"}
                                  variant="outlined"
                                  sx={{ height: 20, "& .MuiChip-label": { px: 0.75, fontSize: "0.65rem" } }}
                                />
                                {!item.passed && item.failQty != null && item.failQty > 0 && (
                                  <Typography variant="caption" color="error.main" component="span">
                                    {t("failQty")}: {formatQty(item.failQty, node.uom)}
                                  </Typography>
                                )}
                              </Stack>
                            }
                            secondary={
                              item.description ? (
                                <Typography
                                  variant="caption"
                                  color="text.secondary"
                                  component="span"
                                  sx={{ display: "block", mt: 0.25, lineHeight: 1.4 }}
                                >
                                  {item.description}
                                </Typography>
                              ) : null
                            }
                          />
                        </ListItem>
                      ))}
                    </List>
                  ) : row.linkKind && row.linkCode ? (
                    <ItemTracingDocLink
                      kind={row.linkKind}
                      code={row.linkCode}
                      id={row.linkId}
                      consoCode={row.consoCode ?? row.linkCode}
                      ticketNo={row.linkTicketNo}
                      targetDate={row.linkTargetDate}
                      openInNewTab
                    />
                  ) : (
                    <Typography
                      component="span"
                      sx={{
                        fontSize: "inherit",
                        fontWeight: row.valueColor && row.valueColor !== "default" ? 700 : undefined,
                        color:
                          row.valueColor && row.valueColor !== "default"
                            ? `${row.valueColor}.main`
                            : undefined,
                      }}
                    >
                      {row.value || "—"}
                    </Typography>
                  )}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>

        {node.traceLotNo ? (
          <Box sx={{ mt: 1.5 }}>
            <ItemTracingLotTraceLink
              label={
                node.kind === "BYPRODUCT"
                  ? t("traceByproductLot")
                  : node.kind === "REPACK"
                    ? t("traceRepackLot")
                    : t("traceMaterialLot")
              }
              lotNo={node.traceLotNo}
              itemCode={node.traceItemCode}
              variant="body2"
              sx={{ display: "inline-block" }}
            />
          </Box>
        ) : null}

        {lifecycleStages.length > 0 && (
          <>
            <Divider sx={{ my: 1.5 }} />
            <Typography variant="subtitle2" fontWeight={700} gutterBottom>
              {t("nodeStockTake")} · {t("stockTakeStageDetail", { count: activeStageCount })}
            </Typography>
            <ItemTracingStockTakeLifecycle stages={lifecycleStages} uom={node.uom} />
          </>
        )}

        {node.meta && (
          <>
            <Divider sx={{ my: 1.5 }} />
            <Typography variant="caption" color="text.secondary">
              {node.meta}
            </Typography>
          </>
        )}
      </Box>
    </Paper>
  );
};

export default ItemTracingNodeDetailPanel;
