"use client";

import { usePurchaseStockInAlerts } from "@/hooks/usePurchaseStockInAlerts";
import AssignmentLateIcon from "@mui/icons-material/AssignmentLate";
import CloseIcon from "@mui/icons-material/Close";
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 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 statusLabel(s: string | null): string {
  const x = (s ?? "").toLowerCase();
  if (x === "pending") return "待處理";
  if (x === "receiving") return "收貨中";
  return s ?? "—";
}

function fmtDt(iso: string | number[] | null): string {
  if (!iso) return "—";
  // Handle array format [year, month, day, hour, minute, second] from API
  if (Array.isArray(iso) && iso.length >= 3) {
    const [y, m, d, h = 0, min = 0, s = 0] = iso;
    const pad = (n: number) => String(n).padStart(2, "0");
    return `${y}-${pad(m)}-${pad(d)} ${pad(h)}:${pad(min)}:${pad(s)}`;
  }
  const d = new Date(iso as string);
  return Number.isNaN(d.getTime()) ? String(iso) : d.toLocaleString();
}

/** Do not pass `stockInLineId` — PoInputGrid opens QC/stock-in modal when that query exists; user should see the list first. */
function poEditHref(row: {
  purchaseOrderId: number;
  purchaseOrderLineId: number;
}): string {
  const q = new URLSearchParams({
    id: String(row.purchaseOrderId),
    polId: String(row.purchaseOrderLineId),
    selectedIds: String(row.purchaseOrderId),
  });
  return `/po/edit?${q.toString()}`;
}

type Props = {
  enabled: boolean;
};

/**
 * Sidebar control: opens dialog with recent pending/receiving PO stock-in lines and links to PO edit.
 */
const PurchaseStockInNavAlerts: React.FC<Props> = ({ enabled }) => {
  const { items, count, loading, reload } = usePurchaseStockInAlerts(enabled);
  const [open, setOpen] = useState(false);

  if (!enabled) return null;

  return (
    <>
      <Tooltip
        title={
          count > 0
            ? `點擊查看 ${count} 筆近日待完成入庫（待處理／收貨中）並前往處理`
            : "近日無待完成採購入庫提醒"
        }
        placement="right"
      >
        <Box sx={{ display: "flex", alignItems: "center", pr: 0.5 }}>
          <IconButton
            size="small"
            aria-label="採購入庫提醒"
            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 ? "fpsmsQuestPulse 1.35s ease-in-out infinite" : "none",
                  "@keyframes fpsmsQuestPulse": {
                    "0%, 100%": { transform: "scale(1)" },
                    "50%": { transform: "scale(1.12)" },
                  },
                },
              }}
            >
              <AssignmentLateIcon 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}>
            <AssignmentLateIcon color="error" />
            <Typography variant="h6" component="span" fontWeight={700}>
              近日待完成採購入庫
            </Typography>
            {loading && (
              <Typography variant="caption" color="text.secondary">
                更新中…
              </Typography>
            )}
          </Stack>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>
            僅列出近幾日建立、狀態為「待處理」或「收貨中」的採購入庫明細。點「前往處理」開啟採購單並定位該明細，可先檢視下方入庫清單再操作。
          </Typography>
          <IconButton
            aria-label="關閉"
            onClick={() => setOpen(false)}
            sx={{ position: "absolute", right: 8, top: 8 }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent dividers>
          {count > items.length && items.length > 0 && (
            <Typography variant="caption" color="text.secondary" sx={{ display: "block", mb: 1 }}>
              共 {count} 筆符合條件，以下顯示最近 {items.length} 筆（可於後端調高單次上限）。
            </Typography>
          )}
          {items.length === 0 && !loading ? (
            <Typography color="text.secondary" sx={{ py: 2 }}>
              目前沒有符合條件的待完成入庫項目。
            </Typography>
          ) : (
            <Table size="small" stickyHeader>
              <TableHead>
                <TableRow>
                  <TableCell>採購單</TableCell>
                  <TableCell>物料</TableCell>
                  <TableCell>狀態</TableCell>
                  <TableCell>建立時間</TableCell>
                  <TableCell>批號</TableCell>
                  <TableCell align="right">操作</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {items.map((r) => (
                  <TableRow key={r.stockInLineId} hover>
                    <TableCell sx={{ fontWeight: 600, whiteSpace: "nowrap" }}>
                      {r.poCode ?? `#${r.purchaseOrderId}`}
                    </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" }}>{fmtDt(r.lineCreated)}</TableCell>
                    <TableCell>{r.lotNo ?? "—"}</TableCell>
                    <TableCell align="right">
                      <Button
                        component={Link}
                        href={poEditHref(r)}
                        target="_blank"
                        rel="noopener noreferrer"
                        size="small"
                        variant="contained"
                        color="primary"
                        endIcon={<OpenInNewIcon sx={{ fontSize: 16 }} />}
                        onClick={() => setOpen(false)}
                      >
                        前往處理
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </DialogContent>
      </Dialog>
    </>
  );
};

export default PurchaseStockInNavAlerts;
