"use client";

import { useJobOrderFgStockInAlerts, PRODUCTION_LOOKBACK_DAYS } from "@/hooks/useJobOrderFgStockInAlerts";
import type { JobOrderFgAlertItem } from "@/hooks/useJobOrderFgStockInAlerts";
import CloseIcon from "@mui/icons-material/Close";
import FactCheckIcon from "@mui/icons-material/FactCheck";
import InventoryIcon from "@mui/icons-material/Inventory";
import OpenInNewIcon from "@mui/icons-material/OpenInNew";
import Badge from "@mui/material/Badge";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import Divider from "@mui/material/Divider";
import IconButton from "@mui/material/IconButton";
import Stack from "@mui/material/Stack";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Tooltip from "@mui/material/Tooltip";
import Typography from "@mui/material/Typography";
import Link from "next/link";
import React, { useState } from "react";

function fmtDt(iso: string | null): string {
  if (!iso) return "—";
  const d = new Date(iso);
  return Number.isNaN(d.getTime()) ? iso : d.toLocaleString();
}

function fmtProcessDate(s: string | null): string {
  if (!s) return "—";
  if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s;
  return fmtDt(s);
}

function qcHref(stockInLineId: number): string {
  return `/productionProcess?openStockInLineId=${stockInLineId}`;
}

function putAwayHref(stockInLineId: number): string {
  return `/putAway?stockInLineId=${stockInLineId}`;
}

function statusLabel(s: string | null): string {
  const x = (s ?? "").toLowerCase();
  if (x === "pending") return "待處理";
  if (x === "receiving") return "收貨中";
  if (x === "received") return "已收貨";
  if (x === "partially_completed") return "部分完成";
  return s ?? "—";
}

function AlertTable({
  title,
  rows,
  mode,
  onRowNavigate,
}: {
  title: string;
  rows: JobOrderFgAlertItem[];
  mode: "qc" | "putAway";
  onRowNavigate: () => void;
}) {
  if (rows.length === 0) return null;
  return (
    <Box sx={{ mb: 2 }}>
      <Typography variant="subtitle2" fontWeight={700} color="text.primary" sx={{ mb: 1 }}>
        {title}（{rows.length}）
      </Typography>
      <Table size="small" stickyHeader>
        <TableHead>
          <TableRow>
            <TableCell>工單</TableCell>
            <TableCell>成品</TableCell>
            <TableCell>狀態</TableCell>
            <TableCell>產程日</TableCell>
            <TableCell>批號</TableCell>
            <TableCell align="right">操作</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map((r) => (
            <TableRow key={`${mode}-${r.stockInLineId}`} hover>
              <TableCell sx={{ fontWeight: 600, whiteSpace: "nowrap" }}>
                {r.jobOrderCode ?? `#${r.jobOrderId}`}
              </TableCell>
              <TableCell>
                <Typography variant="body2" fontWeight={600}>
                  {r.itemNo ?? "—"}
                </Typography>
                <Typography variant="caption" color="text.secondary" display="block">
                  {r.itemName ?? ""}
                </Typography>
              </TableCell>
              <TableCell>{statusLabel(r.status)}</TableCell>
              <TableCell sx={{ whiteSpace: "nowrap" }}>{fmtProcessDate(r.processDate)}</TableCell>
              <TableCell>{r.lotNo ?? "—"}</TableCell>
              <TableCell align="right">
                {mode === "qc" ? (
                  <Button
                    component={Link}
                    href={qcHref(r.stockInLineId)}
                    size="small"
                    variant="contained"
                    color="primary"
                    endIcon={<OpenInNewIcon sx={{ fontSize: 16 }} />}
                    onClick={onRowNavigate}
                  >
                    QC
                  </Button>
                ) : (
                  <Button
                    component={Link}
                    href={putAwayHref(r.stockInLineId)}
                    size="small"
                    variant="contained"
                    color="secondary"
                    startIcon={<InventoryIcon sx={{ fontSize: 16 }} />}
                    endIcon={<OpenInNewIcon sx={{ fontSize: 16 }} />}
                    onClick={onRowNavigate}
                  >
                    上架
                  </Button>
                )}
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </Box>
  );
}

type Props = {
  enabled: boolean;
};

/** FP-MTMS Version Checklist | Functions Ref. No. 52 | v1.0.0 | 2026-08-05 */
const JobOrderFgStockInNavAlerts: React.FC<Props> = ({ enabled }) => {
  const { qcItems, putAwayItems, count, loading, reload } = useJobOrderFgStockInAlerts(enabled);
  const [open, setOpen] = useState(false);

  if (!enabled) return null;

  const onRowNavigate = () => setOpen(false);

  return (
    <>
      <Tooltip
        title={
          count > 0
            ? `點擊查看：待 QC ${qcItems.length}、待上架 ${putAwayItems.length}（與「待 QC 上架」tab 相同：今日往前 ${PRODUCTION_LOOKBACK_DAYS} 天）`
            : `今日往前 ${PRODUCTION_LOOKBACK_DAYS} 天內無待 QC／待上架提醒`
        }
        placement="right"
      >
        <Box sx={{ display: "flex", alignItems: "center", pr: 0.5 }}>
          <IconButton
            size="small"
            aria-label="工單成品 QC 上架提醒"
            onClick={() => {
              void reload();
              setOpen(true);
            }}
            sx={{ color: count > 0 ? "error.main" : "text.disabled" }}
          >
            <Badge
              color="error"
              badgeContent={count > 99 ? "99+" : count}
              invisible={count === 0}
              sx={{
                "& .MuiBadge-badge": {
                  fontWeight: 800,
                  animation: count > 0 ? "fpsmsJoFgPulse 1.35s ease-in-out infinite" : "none",
                  "@keyframes fpsmsJoFgPulse": {
                    "0%, 100%": { transform: "scale(1)" },
                    "50%": { transform: "scale(1.12)" },
                  },
                },
              }}
            >
              <FactCheckIcon fontSize="small" />
            </Badge>
          </IconButton>
        </Box>
      </Tooltip>

      <Dialog open={open} onClose={() => setOpen(false)} maxWidth="md" fullWidth scroll="paper">
        <DialogTitle sx={{ pr: 6 }}>
          <Stack direction="row" alignItems="center" spacing={1}>
            <FactCheckIcon color="error" />
            <Typography variant="h6" component="span" fontWeight={700}>
              工單成品：待 QC／待上架
            </Typography>
            {loading && (
              <Typography variant="caption" color="text.secondary">
                更新中…
              </Typography>
            )}
          </Stack>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>
            與產程頁<strong>「待 QC 上架」</strong>相同資料來源：搜索日為<strong>今日</strong>、往前
            <strong> {PRODUCTION_LOOKBACK_DAYS} </strong>天產程；工序全完成、入庫未完成／未拒絕。待 QC：尚未進入已收貨；待上架：已收貨或部分完成入庫。
          </Typography>
          <IconButton
            aria-label="關閉"
            onClick={() => setOpen(false)}
            sx={{ position: "absolute", right: 8, top: 8 }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent dividers>
          {qcItems.length === 0 && putAwayItems.length === 0 && !loading ? (
            <Typography color="text.secondary" sx={{ py: 2 }}>
              目前沒有符合條件的項目。
            </Typography>
          ) : (
            <>
              <AlertTable
                title="待 QC（等同完成QC工單列表中可開 QC 的階段）"
                rows={qcItems}
                mode="qc"
                onRowNavigate={onRowNavigate}
              />
              {qcItems.length > 0 && putAwayItems.length > 0 && <Divider sx={{ my: 2 }} />}
              <AlertTable
                title="待上架（已完成 QC、待掃碼上架）"
                rows={putAwayItems}
                mode="putAway"
                onRowNavigate={onRowNavigate}
              />
            </>
          )}
        </DialogContent>
      </Dialog>
    </>
  );
};

export default JobOrderFgStockInNavAlerts;
