"use client";

import React, { useCallback, useEffect, useRef, useState } from "react";
import {
  Alert,
  Box,
  Chip,
  CircularProgress,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography,
} from "@mui/material";
import { NEXT_PUBLIC_API_URL } from "@/config/api";
import { clientAuthFetch } from "@/app/utils/clientAuthFetch";
import { arrayToDateTimeString } from "@/app/utils/formatUtil";
import dayjs from "dayjs";

function formatApiDateTime(value: unknown): string {
  if (value == null) return "—";
  if (Array.isArray(value)) {
    return arrayToDateTimeString(value as (number | undefined)[]);
  }
  const d = dayjs(value as string | number);
  return d.isValid() ? d.format("YYYY-MM-DD HH:mm:ss") : "—";
}

type PrinterRow = {
  id: number;
  code?: string;
  name?: string;
  type?: string;
  brand?: string;
  ip?: string;
  port?: number;
  status: "online" | "offline" | "unconfigured" | "unchecked";
  latencyMs?: number;
  errorMessage?: string;
  lastCheckAt?: string;
};

type PrinterSummary = {
  total: number;
  online: number;
  offline: number;
  unconfigured: number;
  unchecked: number;
};

const PRINTER_STATUS_LABEL: Record<
  string,
  { label: string; color: "success" | "warning" | "error" | "default" }
> = {
  online: { label: "連線正常", color: "success" },
  offline: { label: "離線", color: "error" },
  unconfigured: { label: "未設定 IP", color: "warning" },
  unchecked: { label: "未檢查", color: "default" },
};

type Props = {
  active: boolean;
  /** Increment from parent to trigger an immediate connectivity check. */
  refreshAt?: number;
};

export default function PrinterMonitorTab({ active, refreshAt = 0 }: Props) {
  const [printers, setPrinters] = useState<PrinterRow[]>([]);
  const [warnings, setWarnings] = useState<PrinterRow[]>([]);
  const [summary, setSummary] = useState<PrinterSummary | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const inFlightRef = useRef(false);

  const runCheck = useCallback(async () => {
    if (inFlightRef.current) return;
    inFlightRef.current = true;
    setLoading(true);
    setError(null);
    try {
      const response = await clientAuthFetch(
        `${NEXT_PUBLIC_API_URL}/printer-monitor/check`,
        { method: "POST" }
      );
      if (response.status === 401 || response.status === 403) return;
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      const data = await response.json();
      setPrinters(Array.isArray(data.printers) ? data.printers : []);
      setWarnings(Array.isArray(data.warnings) ? data.warnings : []);
      setSummary(data.summary ?? null);
    } catch (e) {
      console.error("printer monitor check", e);
      setError("無法檢查印表機連線");
    } finally {
      setLoading(false);
      inFlightRef.current = false;
    }
  }, []);

  useEffect(() => {
    if (!active) return;
    void runCheck();
    const id = window.setInterval(() => void runCheck(), 120_000);
    return () => window.clearInterval(id);
  }, [active, runCheck]);

  useEffect(() => {
    if (!active || refreshAt <= 0) return;
    void runCheck();
  }, [refreshAt, active, runCheck]);

  const offlineCount = summary?.offline ?? warnings.length;

  return (
    <div className="space-y-4">
      <Typography variant="body2" color="text.secondary">
        監控「印表機」設定中所有未刪除的印表機，以 TCP 連線至 IP:Port（預設 9100）檢測是否可連線。每
        2 分鐘自動檢查；離線印表機會顯示於下方警告清單並寫入事件記錄。
      </Typography>

      {offlineCount > 0 && (
        <Alert severity="error">
          有 {offlineCount} 台印表機無法連線，請檢查電源、網路或 IP/Port 設定。
        </Alert>
      )}

      {summary && (
        <Box className="flex flex-wrap gap-2">
          <Chip size="small" label={`總數 ${summary.total}`} />
          <Chip size="small" color="success" label={`正常 ${summary.online}`} />
          <Chip size="small" color="error" label={`離線 ${summary.offline}`} />
          <Chip size="small" color="warning" label={`未設定 IP ${summary.unconfigured}`} />
          {summary.unchecked > 0 && (
            <Chip size="small" label={`未檢查 ${summary.unchecked}`} />
          )}
        </Box>
      )}

      {error && <Alert severity="error">{error}</Alert>}

      {warnings.length > 0 && (
        <div className="space-y-2">
          <Typography variant="subtitle2" fontWeight={600} color="error">
            離線警告清單
          </Typography>
          <TableContainer className="rounded-lg border border-red-200 bg-red-50/50 dark:border-red-900 dark:bg-red-950/20">
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell>印表機</TableCell>
                  <TableCell>類型</TableCell>
                  <TableCell>IP:Port</TableCell>
                  <TableCell>錯誤</TableCell>
                  <TableCell>最後檢查</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {warnings.map((row) => (
                  <TableRow key={row.id} hover>
                    <TableCell>
                      <Typography variant="body2" fontWeight={600}>
                        {row.name || row.code || `#${row.id}`}
                      </Typography>
                      {row.code && row.name && (
                        <Typography variant="caption" color="text.secondary">
                          {row.code}
                        </Typography>
                      )}
                    </TableCell>
                    <TableCell>
                      {[row.type, row.brand].filter(Boolean).join(" / ") || "—"}
                    </TableCell>
                    <TableCell>
                      {row.ip ? `${row.ip}:${row.port ?? 9100}` : "—"}
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" color="error">
                        {row.errorMessage ?? "無法連線"}
                      </Typography>
                    </TableCell>
                    <TableCell>{formatApiDateTime(row.lastCheckAt)}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </div>
      )}

      <Typography variant="subtitle2" fontWeight={600}>
        全部印表機
      </Typography>
      <TableContainer className="rounded-lg border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-800">
        <Table size="small">
          <TableHead>
            <TableRow>
              <TableCell>狀態</TableCell>
              <TableCell>印表機</TableCell>
              <TableCell>類型</TableCell>
              <TableCell>IP:Port</TableCell>
              <TableCell align="right">延遲 (ms)</TableCell>
              <TableCell>最後檢查</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {loading && printers.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} align="center" sx={{ py: 4 }}>
                  <CircularProgress size={28} />
                </TableCell>
              </TableRow>
            ) : printers.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} align="center" sx={{ py: 4 }}>
                  沒有印表機資料
                </TableCell>
              </TableRow>
            ) : (
              printers.map((row) => {
                const st =
                  PRINTER_STATUS_LABEL[row.status] ?? PRINTER_STATUS_LABEL.unchecked;
                return (
                  <TableRow key={row.id} hover>
                    <TableCell>
                      <Chip size="small" color={st.color} label={st.label} />
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" fontWeight={600}>
                        {row.name || row.code || `#${row.id}`}
                      </Typography>
                      {row.code && row.name && (
                        <Typography variant="caption" color="text.secondary">
                          {row.code}
                        </Typography>
                      )}
                    </TableCell>
                    <TableCell>
                      {[row.type, row.brand].filter(Boolean).join(" / ") || "—"}
                    </TableCell>
                    <TableCell>
                      {row.ip ? `${row.ip}:${row.port ?? 9100}` : "—"}
                    </TableCell>
                    <TableCell align="right">
                      {row.latencyMs != null ? row.latencyMs : "—"}
                    </TableCell>
                    <TableCell>{formatApiDateTime(row.lastCheckAt)}</TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </TableContainer>

      {loading && printers.length > 0 && (
        <Box className="flex justify-center py-2">
          <CircularProgress size={24} />
        </Box>
      )}
    </div>
  );
}
