"use client";

import React, { useCallback, useMemo, useRef, useState } from "react";
import {
  Alert,
  Box,
  Button,
  Chip,
  CircularProgress,
  MenuItem,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
  Paper,
} from "@mui/material";
import { useTranslation } from "react-i18next";
import { Check, Clock, X } from "lucide-react";
import type {
  ItemUnitStatus,
  MasterDataIssue,
  MasterDataIssueCode,
} from "@/app/api/masterDataIssues";
import MasterDataIssueDetailDialog from "./MasterDataIssueDetailDialog";
import {
  buildDisplayLines,
  materialBomSubtitle,
  needsDetailButton,
  primaryTitle,
} from "./buildDisplayLines";
import {
  formatItemLabel,
  groupBomTabIssues,
  groupItemTabIssues,
  type MasterDataIssueGroup,
} from "./groupMasterDataIssues";

export type MasterDataIssuesPanelMode = "item" | "bom";

interface ItemUnitCellProps {
  status: ItemUnitStatus;
  value: string;
  modifiedAt: string;
  activeLabel: string;
  inactiveLabel: string;
  missingLabel: string;
}

function splitUomDisplay(value: string): { code: string; desc: string } {
  const trimmed = value?.trim() ?? "";
  if (!trimmed || trimmed === "-") return { code: "-", desc: "-" };
  const sep = trimmed.indexOf(" / ");
  if (sep >= 0) {
    return {
      code: trimmed.slice(0, sep).trim() || "-",
      desc: trimmed.slice(sep + 3).trim() || "-",
    };
  }
  return { code: trimmed, desc: "-" };
}

const ItemUnitStatusCell: React.FC<ItemUnitCellProps> = ({
  status,
  value,
  modifiedAt,
  activeLabel,
  inactiveLabel,
  missingLabel,
}) => {
  const isActive = status === "OK";
  const isMissing = status === "MISSING";
  const isDeleted = status === "DELETED";
  const { code, desc } = splitUomDisplay(value);

  const badgeBg = isActive ? "success.50" : isMissing ? "grey.100" : "error.50";
  const badgeColor = isActive ? "success.dark" : isMissing ? "text.secondary" : "error.dark";
  const badgeText = isActive ? activeLabel : isMissing ? missingLabel : inactiveLabel;

  return (
    <Stack spacing={0.75} sx={{ minWidth: 0 }}>
      <Box sx={{ minHeight: 20, display: "flex", alignItems: "flex-end" }}>
        <Typography
          variant="body2"
          sx={{
            fontWeight: 700,
            color: "text.primary",
            lineHeight: 1.3,
          }}
        >
          {desc}
        </Typography>
      </Box>
      <Box sx={{ minHeight: 20, display: "flex", alignItems: "flex-start" }}>
        <Typography variant="body2" color="text.secondary" sx={{ lineHeight: 1.35 }}>
          {code}
        </Typography>
      </Box>
      <Box sx={{ minHeight: 28, display: "flex", alignItems: "center" }}>
        <Box
          sx={{
            display: "inline-flex",
            alignItems: "center",
            gap: 0.5,
            px: 1,
            py: 0.35,
            borderRadius: 1,
            width: "fit-content",
            bgcolor: badgeBg,
            color: badgeColor,
          }}
        >
          {isActive ? <Check size={14} strokeWidth={2.5} /> : null}
          {isDeleted ? <X size={14} strokeWidth={2.5} /> : null}
          <Typography variant="caption" sx={{ fontWeight: 600, lineHeight: 1 }}>
            {badgeText}
          </Typography>
        </Box>
      </Box>
      <Box sx={{ minHeight: 18, display: "flex", alignItems: "center", gap: 0.5 }}>
        {!isMissing ? (
          <>
            <Clock size={12} style={{ flexShrink: 0, opacity: 0.55 }} />
            <Typography
              variant="caption"
              color="text.secondary"
              sx={{ lineHeight: 1.3, whiteSpace: "nowrap" }}
            >
              {modifiedAt}
            </Typography>
          </>
        ) : (
          <Typography variant="caption" color="text.secondary">
            -
          </Typography>
        )}
      </Box>
    </Stack>
  );
};

const itemUnitCellSx = {
  verticalAlign: "top" as const,
  width: "18%",
  minWidth: 155,
};

interface Props {
  mode: MasterDataIssuesPanelMode;
  issues: MasterDataIssue[];
  loading: boolean;
  loadError: string | null;
  onRefresh: () => void;
}

const MasterDataIssuesPanel: React.FC<Props> = ({
  mode,
  issues,
  loading,
  loadError,
  onRefresh,
}) => {
  const { t } = useTranslation("masterDataIssue");
  const inFlightRef = useRef(false);
  const [scopeFilter, setScopeFilter] = useState<string>("ALL");
  const [search, setSearch] = useState("");
  const [detailGroup, setDetailGroup] = useState<MasterDataIssueGroup | null>(
    null,
  );

  const issueMessage = useCallback(
    (code: MasterDataIssueCode | string) =>
      t(`masterDataIssue_${code}`, { defaultValue: code }),
    [t],
  );

  const scopeLabel = useCallback(
    (scope: string) =>
      t(`masterDataIssue_scope_${scope}`, { defaultValue: scope }),
    [t],
  );

  const isPickingOnlyIssue = useCallback((issueCode: string) => {
    return issueCode.includes("PICKING");
  }, []);

  const filteredIssues = useMemo(() => {
    const q = search.trim().toLowerCase();
    return issues.filter((row) => {
      // Item tab only shows 4 units (base/stock/purchase/sales), so exclude picking-only issues.
      if (mode === "item" && isPickingOnlyIssue(row.issueCode)) {
        return false;
      }
      if (mode === "bom" && scopeFilter !== "ALL" && row.scope !== scopeFilter) {
        return false;
      }
      if (!q) return true;
      const hay = [
        row.bomCode,
        row.bomName,
        row.itemCode,
        row.itemName,
        row.issueCode,
        row.expectedValue,
        row.actualValue,
      ]
        .filter(Boolean)
        .join(" ")
        .toLowerCase();
      return hay.includes(q);
    });
  }, [issues, mode, scopeFilter, search, isPickingOnlyIssue]);

  const groups = useMemo(() => {
    return mode === "item"
      ? groupItemTabIssues(filteredIssues)
      : groupBomTabIssues(filteredIssues);
  }, [filteredIssues, mode]);

  const groupsWithLines = useMemo(
    () =>
      groups.map((g) => ({
        group: g,
        lines: buildDisplayLines(g, t, issueMessage),
        showDetail: false as boolean,
      })).map((entry) => ({
        ...entry,
        showDetail: needsDetailButton(entry.group, entry.lines),
      })),
    [groups, t, issueMessage],
  );

  const formatModifiedAt = useCallback((value?: string | null) => {
    if (!value) return "-";
    const d = new Date(value);
    if (Number.isNaN(d.getTime())) return value;
    return d.toLocaleString();
  }, []);

  const buildBomCompareRows = useCallback((group: MasterDataIssueGroup) => {
    const rows = group.issues
      .filter((r) =>
        [
          "BOM_OUTPUT_UOM_MISMATCH_SALES",
          "BOM_MATERIAL_SALES_UOM_MISMATCH",
          "BOM_MATERIAL_STOCK_UOM_MISMATCH",
          "BOM_MATERIAL_BASE_UOM_MISMATCH",
        ].includes(r.issueCode),
      )
      .map((r) => {
        const unitLabel =
          r.issueCode === "BOM_OUTPUT_UOM_MISMATCH_SALES"
            ? t("masterDataIssue_unit_output", { defaultValue: "产出单位" })
            : r.issueCode === "BOM_MATERIAL_SALES_UOM_MISMATCH"
              ? t("masterDataIssue_unit_sales")
              : r.issueCode === "BOM_MATERIAL_STOCK_UOM_MISMATCH"
                ? t("masterDataIssue_unit_stock")
                : t("masterDataIssue_unit_base");
        return {
          key: `${r.issueCode}-${r.bomMaterialId ?? "x"}`,
          unitLabel,
          bomValue: r.actualValue ?? "-",
          itemValue: r.expectedValue ?? "-",
        };
      });
    if (rows.length > 0) return rows;
    return [
      {
        key: "fallback",
        unitLabel: t("masterDataIssue_unit_output", { defaultValue: "产出单位" }),
        bomValue: "-",
        itemValue: "-",
      },
    ];
  }, [t]);

interface BomCompareRow {
  key: string;
  unitLabel: string;
  bomValue: string;
  itemValue: string;
}

interface BomCompareColumnProps {
  rows: BomCompareRow[];
  valueKey: "bomValue" | "itemValue";
  labelColor: string;
  valueColor: string;
}

const BomCompareColumn: React.FC<BomCompareColumnProps> = ({
  rows,
  valueKey,
  labelColor,
  valueColor,
}) => (
  <Stack spacing={1.5}>
    {rows.map((row) => (
      <Stack key={row.key} spacing={0.35}>
        <Typography
          variant="body2"
          sx={{ color: labelColor, fontWeight: 600, lineHeight: 1.3 }}
        >
          {row.unitLabel}
        </Typography>
        <Typography
          variant="body2"
          sx={{ color: valueColor, fontWeight: 500, lineHeight: 1.4, wordBreak: "break-word" }}
        >
          {row[valueKey]}
        </Typography>
      </Stack>
    ))}
  </Stack>
);

  const parseUnitStatus = useCallback((raw?: string | null): ItemUnitStatus => {
    if (raw === "OK" || raw === "DELETED" || raw === "MISSING") return raw;
    return "MISSING";
  }, []);

  const unitSnapshotFromGroup = useCallback((group: MasterDataIssueGroup) => {
    const row = group.issues[0];
    const cell = (
      value: string | null | undefined,
      status: string | null | undefined,
      modifiedAt: string | null | undefined,
    ) => {
      const unitStatus = parseUnitStatus(status);
      return {
        status: unitStatus,
        value: value?.trim() ? value : "-",
        modifiedAt: formatModifiedAt(modifiedAt),
      };
    };
    return {
      base: cell(row?.baseUnitValue, row?.baseUnitStatus, row?.baseUnitModifiedAt),
      stock: cell(row?.stockUnitValue, row?.stockUnitStatus, row?.stockUnitModifiedAt),
      purchase: cell(row?.purchaseUnitValue, row?.purchaseUnitStatus, row?.purchaseUnitModifiedAt),
      sales: cell(row?.salesUnitValue, row?.salesUnitStatus, row?.salesUnitModifiedAt),
    };
  }, [formatModifiedAt, parseUnitStatus]);

  const clipboardText = useMemo(() => {
    return groupsWithLines
      .map(({ group, lines }) => {
        const title = primaryTitle(group);
        return `${title}\n${lines.map((l) => `  ${l}`).join("\n")}`;
      })
      .join("\n\n");
  }, [groupsWithLines]);

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(clipboardText);
    } catch {
      console.warn("clipboard write failed");
    }
  };

  const handleRefreshClick = () => {
    if (inFlightRef.current) return;
    inFlightRef.current = true;
    Promise.resolve(onRefresh()).finally(() => {
      inFlightRef.current = false;
    });
  };

  return (
    <Box>
      <Stack
        direction={{ xs: "column", sm: "row" }}
        spacing={1.5}
        alignItems={{ sm: "center" }}
        sx={{ mb: 2 }}
        flexWrap="wrap"
      >
        <Typography variant="body2" color="text.secondary">
          {t("masterDataIssue_group_count", {
            groups: groups.length,
            issues: filteredIssues.length,
          })}
        </Typography>
        <Box sx={{ flex: 1 }} />
        <TextField
          size="small"
          label={t("masterDataIssue_search")}
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          sx={{ minWidth: 180 }}
        />
        {mode === "bom" ? (
          <TextField
            select
            size="small"
            label={t("masterDataIssue_filter_type")}
            value={scopeFilter}
            onChange={(e) => setScopeFilter(e.target.value)}
            sx={{ minWidth: 140 }}
          >
            <MenuItem value="ALL">{t("masterDataIssue_filter_all")}</MenuItem>
            <MenuItem value="BOM">{scopeLabel("BOM")}</MenuItem>
            <MenuItem value="BOM_MATERIAL">{scopeLabel("BOM_MATERIAL")}</MenuItem>
          </TextField>
        ) : null}
        <Button
          size="small"
          variant="outlined"
          disabled={loading}
          onClick={handleRefreshClick}
        >
          {loading ? t("masterDataIssue_refreshing") : t("masterDataIssue_refresh")}
        </Button>
        <Button
          size="small"
          variant="outlined"
          disabled={groupsWithLines.length === 0}
          onClick={() => void handleCopy()}
        >
          {t("masterDataIssue_copy")}
        </Button>
      </Stack>

      {loadError && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {loadError}
        </Alert>
      )}

      {loading && issues.length === 0 && !loadError ? (
        <Box sx={{ display: "flex", justifyContent: "center", py: 6 }}>
          <CircularProgress size={32} />
        </Box>
      ) : null}

      {!loading && !loadError && groupsWithLines.length === 0 ? (
        <Typography variant="body2" color="text.secondary">
          {t("masterDataIssue_empty")}
        </Typography>
      ) : null}

      {groupsWithLines.length > 0 ? (
        <TableContainer component={Paper} variant="outlined">
          <Table
            size="small"
            stickyHeader
            sx={mode === "item" ? { tableLayout: "fixed", width: "100%" } : undefined}
          >
            <TableHead>
              <TableRow>
                <TableCell sx={{ width: "28%" }}>
                  {mode === "item"
                    ? t("masterDataIssue_col_item")
                    : t("masterDataIssue_col_subject")}
                </TableCell>
                {mode === "bom" ? (
                  <>
                    <TableCell>{t("masterDataIssue_col_bom_uom", { defaultValue: "BOM UOM" })}</TableCell>
                    <TableCell>{t("masterDataIssue_col_item_uom", { defaultValue: "Item 正确 UOM" })}</TableCell>
                  </>
                ) : (
                  <>
                    <TableCell sx={itemUnitCellSx}>{t("masterDataIssue_unit_base")}</TableCell>
                    <TableCell sx={itemUnitCellSx}>{t("masterDataIssue_unit_stock")}</TableCell>
                    <TableCell sx={itemUnitCellSx}>{t("masterDataIssue_unit_purchase")}</TableCell>
                    <TableCell sx={itemUnitCellSx}>{t("masterDataIssue_unit_sales")}</TableCell>
                  </>
                )}

              </TableRow>
            </TableHead>
            <TableBody>
              {groupsWithLines.map(({ group, showDetail }) => {
                const matSubtitle = materialBomSubtitle(group, t);
                const unitSnapshot = unitSnapshotFromGroup(group);
                const bomCompareRows = buildBomCompareRows(group);
                return (
                <TableRow key={group.groupKey}>
                  <TableCell sx={mode === "item" ? { verticalAlign: "top" } : undefined}>
                    {mode === "item" ? (
                      <Stack spacing={0.35} sx={{ minWidth: 0 }}>
                        {group.itemCode?.trim() ? (
                          <Typography variant="body2" sx={{ fontWeight: 600 }}>
                            {group.itemCode.trim()}
                          </Typography>
                        ) : null}
                        {group.itemName?.trim() ? (
                          <Typography
                            variant="body2"
                            sx={{ lineHeight: 1.45, wordBreak: "break-word" }}
                          >
                            {group.itemName.trim()}
                          </Typography>
                        ) : !group.itemCode?.trim() ? (
                          <Typography variant="body2" sx={{ fontWeight: 600 }}>
                            {formatItemLabel(group)}
                          </Typography>
                        ) : null}
                      </Stack>
                    ) : (
                      <Typography variant="body2" sx={{ fontWeight: 600 }}>
                        {primaryTitle(group)}
                      </Typography>
                    )}
                    {mode === "bom" && group.groupType === "bom_header" ? (
                      <Stack spacing={0.5} sx={{ mt: 0.5 }}>
                        <Box>
                          <Chip
                            size="small"
                            label={scopeLabel("BOM")}
                            color="primary"
                            variant="outlined"
                          />
                        </Box>
                        {group.itemCode?.trim() ? (
                          <Typography variant="caption" color="text.secondary" display="block">
                            
                            {[group.itemCode.trim(), group.itemName?.trim()].filter(Boolean).join(" · ")}
                          </Typography>
                        ) : null}
                      </Stack>
                    ) : null}
                    {mode === "bom" && group.groupType === "bom_material" ? (
                      <Stack spacing={0.5} sx={{ mt: 0.5 }}>
                        <Box>
                          <Chip
                            size="small"
                            label={scopeLabel("BOM_MATERIAL")}
                            color="secondary"
                            variant="outlined"
                          />
                        </Box>
                        {matSubtitle ? (
                          <Typography variant="caption" color="text.secondary" display="block">
                            {matSubtitle}
                          </Typography>
                        ) : null}
                      </Stack>
                    ) : null}
                  </TableCell>
                  {mode === "bom" ? (
                    <>
                      <TableCell sx={{ verticalAlign: "top" }}>
                        <BomCompareColumn
                          rows={bomCompareRows}
                          valueKey="bomValue"
                          labelColor="error.main"
                          valueColor="error.dark"
                        />
                      </TableCell>
                      <TableCell sx={{ verticalAlign: "top" }}>
                        <BomCompareColumn
                          rows={bomCompareRows}
                          valueKey="itemValue"
                          labelColor="success.main"
                          valueColor="success.dark"
                        />
                      </TableCell>
                    </>
                  ) : (
                    <>
                      {(
                        [
                          ["base", unitSnapshot.base],
                          ["stock", unitSnapshot.stock],
                          ["purchase", unitSnapshot.purchase],
                          ["sales", unitSnapshot.sales],
                        ] as const
                      ).map(([key, unit]) => (
                        <TableCell key={key} sx={itemUnitCellSx}>
                          <ItemUnitStatusCell
                            status={unit.status}
                            value={unit.value}
                            modifiedAt={unit.modifiedAt}
                            activeLabel={t("masterDataIssue_unit_active", {
                              defaultValue: "啟用",
                            })}
                            inactiveLabel={t("masterDataIssue_unit_inactive", {
                              defaultValue: "已停用",
                            })}
                            missingLabel={t("masterDataIssue_unit_missing", {
                              defaultValue: "沒有單位",
                            })}
                          />
                        </TableCell>
                      ))}
                    </>
                  )}
    
                </TableRow>
              );
              })}
            </TableBody>
          </Table>
        </TableContainer>
      ) : null}

      <MasterDataIssueDetailDialog
        open={detailGroup != null}
        group={detailGroup}
        onClose={() => setDetailGroup(null)}
      />
    </Box>
  );
};

export default MasterDataIssuesPanel;
