import React, { useState, useEffect, useCallback, useRef } from "react";
import { Document, Page } from "react-pdf";
import "react-pdf/dist/esm/Page/AnnotationLayer.css";
import "./UI8.css";
import "../../assets/css/basic.css";
import { useNavigate } from "react-router-dom";
import ConfirmButton from "../../components/ConfirmButton";
import DuplexToggle from "../../components/DuplexToggle";
import ui8A from "../../assets/ui8A.png";
import ui8B from "../../assets/ui8B.png";
import { getDaojiandanPdf } from "../../api/hisApi";

const PREFERRED_PRINTER_KEY = "preferredPrinterName";
const PREFERRED_DUPLEX_KEY = "preferredDuplex";

type PrinterInfo = ElectronPrinterInfo;

// 独立的 PDF 渲染组件，使用 React.memo 避免不必要的重新渲染
const PdfRenderer = React.memo<{
  pdfFiles: string[];
  loading: boolean;
  error: string;
  pageCounts: Record<number, number>;
  onPageCountUpdate: (index: number, numPages: number) => void;
  onDocumentLoadError: (error: Error) => void;
}>(({ pdfFiles, loading, error, pageCounts, onPageCountUpdate, onDocumentLoadError }) => {
  return (
    <>
      {loading && <div className="ui8-loading">PDF加载中...</div>}
      {error && <div className="ui8-error">{error}</div>}

      {!loading &&
        !error &&
        pdfFiles.map((fileData, index) => (
          <div key={index} style={{ marginBottom: "20px", width: "100%" }}>
            <Document
              file={fileData}
              loading=""
              onLoadSuccess={({ numPages }) => onPageCountUpdate(index, numPages)}
              onLoadError={onDocumentLoadError}
            >
              {Array.from({ length: pageCounts[index] || 0 }, (_, pageIndex) => (
                <div key={`pdf-${index}-page-${pageIndex + 1}`} className="ui8-pdf-page-wrapper">
                  <Page
                    pageNumber={pageIndex + 1}
                    renderTextLayer={false}
                    renderAnnotationLayer={false}
                    className="ui8-pdf-page"
                    width={920}
                  />
                </div>
              ))}
            </Document>
          </div>
        ))}
    </>
  );
});

PdfRenderer.displayName = "PdfRenderer";

const UI8: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string>("");
  const [isPrinting, setIsPrinting] = useState<boolean>(false);
  const [pdfFiles, setPdfFiles] = useState<string[]>([]);
  const [pageCounts, setPageCounts] = useState<Record<number, number>>({});
  const [originPdfUrls, setOriginPdfUrls] = useState<string[]>([]);
  const [printers, setPrinters] = useState<PrinterInfo[]>([]);
  const [selectedPrinter, setSelectedPrinter] = useState<string>("");
  const [printersLoading, setPrintersLoading] = useState<boolean>(false);
  const [printerError, setPrinterError] = useState<string>("");
  const [isPrinterDropdownOpen, setIsPrinterDropdownOpen] =
    useState<boolean>(false);
  const printerDropdownRef = useRef<HTMLDivElement | null>(null);
  const pdfContainerRef = useRef<HTMLDivElement | null>(null);
  const [isRightSectionHidden, setIsRightSectionHidden] = useState(false);
  const [duplexEnabled, setDuplexEnabled] = useState<boolean>(false);

  const getExamId = () => {
    const storedId = localStorage.getItem("selectedExamId");
    return storedId || "";
  };

  const arrayBufferToDataUrl = (arrayBuffer: ArrayBuffer) => {
    return new Promise<string>((resolve, reject) => {
      const blob = new Blob([arrayBuffer], { type: "application/pdf" });
      const reader = new FileReader();
      reader.onloadend = () => {
        if (typeof reader.result === "string") {
          resolve(reader.result);
        } else {
          reject(new Error("PDF 转换失败"));
        }
      };
      reader.onerror = () => reject(new Error("PDF 读取失败"));
      reader.readAsDataURL(blob);
    });
  };

  const fetchPdfDataUrl = async (url: string) => {
    try {
      if (window.electronAPI?.fetchPdf) {
        window.electronAPI.log("info", `[UI8] 通过 Electron 获取 PDF: ${url}`);
        const result = await window.electronAPI.fetchPdf(url);
        if (result.success && result.data) {
          const cleanBase64 = result.data.replace(/\s/g, "");
          return `data:application/pdf;base64,${cleanBase64}`;
        }
        throw new Error(result.error || "fetchPdf 返回失败");
      }

      window.electronAPI?.log("info", `[UI8] 通过 fetch 获取 PDF: ${url}`);
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`网络请求失败: ${response.status}`);
      }
      const arrayBuffer = await response.arrayBuffer();
      return await arrayBufferToDataUrl(arrayBuffer);
    } catch (err) {
      throw new Error(`获取 PDF 失败: ${(err as Error).message}`);
    }
  };

  // 加载PDF数据
  useEffect(() => {
    const loadPdf = async () => {
      try {
        setLoading(true);
        setError("");
        setPdfFiles([]);
        setPageCounts({});

        const examId = getExamId();
        let pdfUrl = "";
        const consentSignature = localStorage.getItem("consentSignature");
        if (consentSignature) {
          pdfUrl = consentSignature;
        } else {
          window.electronAPI?.log("info", `[UI8] 开始获取导检单 PDF，exam_id=${examId}`);
          const res = await getDaojiandanPdf(parseInt(examId, 10));
          if (res.Status !== 200) {
            throw new Error(res.Message || "获取导检单PDF失败");
          }
          pdfUrl = res.Data?.pdf_url;
          if (!pdfUrl) {
            throw new Error("未获取到导检单 PDF");
          }
        }

        setOriginPdfUrls([pdfUrl]);

        window.electronAPI?.log("info", `[UI8] 下载导检单 PDF: ${pdfUrl}`);
        const dataUrl = await fetchPdfDataUrl(pdfUrl);
        setPdfFiles([dataUrl]);
      } catch (err) {
        const errorMsg = `导检单PDF获取失败: ${(err as Error).message || err}`;
        console.error(errorMsg);
        window.electronAPI?.log("error", `[UI8] ${errorMsg}`);
        setError("PDF 获取失败，请稍后重试");
      } finally {
        setLoading(false);
      }
    };

    loadPdf();
  }, []);

  // 加载打印机列表并恢复上次选择
  useEffect(() => {
    if (!window.electronAPI?.getPrinters) {
      setPrinterError("当前环境不支持打印机列表读取");
      return;
    }

    let isMounted = true;
    const fetchPrinters = async () => {
      setPrintersLoading(true);
      try {
        window.electronAPI.log("info", "[UI8] 开始获取打印机列表");
        const result = await window.electronAPI.getPrinters();
        if (!isMounted) return;
        if (!result.success) {
          throw new Error(result.error || "获取打印机列表失败");
        }

        const list = result.printers || [];
        setPrinters(list);

        const stored = localStorage.getItem(PREFERRED_PRINTER_KEY);
        const matchedStored =
          stored && list.some((printer) => printer.name === stored)
            ? stored
            : "";
        const defaultPrinter =
          matchedStored ||
          list.find((printer) => printer.isDefault)?.name ||
          list[0]?.name ||
          "";

        if (defaultPrinter) {
          setSelectedPrinter(defaultPrinter);
          localStorage.setItem(PREFERRED_PRINTER_KEY, defaultPrinter);
          window.electronAPI.log(
            "info",
            `[UI8] 默认打印机设置为 ${defaultPrinter}`
          );
        }
        setPrinterError("");
      } catch (error) {
        const msg =
          (error as Error).message || "打印机列表获取失败，请联系管理员";
        if (isMounted) {
          setPrinterError(msg);
        }
        window.electronAPI.log("error", `[UI8] ${msg}`);
      } finally {
        if (isMounted) {
          setPrintersLoading(false);
        }
      }
    };

    fetchPrinters();

    // 恢复双面打印设置
    const storedDuplex = localStorage.getItem(PREFERRED_DUPLEX_KEY);
    if (storedDuplex === "true") {
      setDuplexEnabled(true);
    }

    return () => {
      isMounted = false;
    };
  }, []);

  const handlePrinterChange = useCallback(
    (printerName: string) => {
      setSelectedPrinter(printerName);
      localStorage.setItem(PREFERRED_PRINTER_KEY, printerName);
      window.electronAPI?.log(
        "info",
        `[UI8] 用户选择打印机: ${printerName}`
      );
      setIsPrinterDropdownOpen(false);
    },
    []
  );

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        printerDropdownRef.current &&
        !printerDropdownRef.current.contains(event.target as Node)
      ) {
        setIsPrinterDropdownOpen(false);
      }
    };

    if (isPrinterDropdownOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    } else {
      document.removeEventListener("mousedown", handleClickOutside);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isPrinterDropdownOpen]);

  const togglePrinterDropdown = useCallback(() => {
    if (printersLoading || printers.length === 0) return;
    setIsPrinterDropdownOpen((prev) => !prev);
  }, [printers.length, printersLoading]);

  const handlePdfScroll = useCallback(() => {
    const container = pdfContainerRef.current;
    if (!container) return;
    const shouldHide = container.scrollTop > 20;
    setIsRightSectionHidden((prev) => {
      if (prev === shouldHide) return prev;
      return shouldHide;
    });
  }, []);

  useEffect(() => {
    setIsRightSectionHidden(false);
    if (pdfContainerRef.current) {
      pdfContainerRef.current.scrollTop = 0;
    }
  }, [pdfFiles]);

  // 打印PDF功能
  const handleConfirm = useCallback(async () => {
    // 避免重复点击导致多次打印
    if (isPrinting) {
      window.electronAPI?.log("warn", "[UI8] 检测到重复打印点击，已忽略");
      return;
    }

    if (!window.electronAPI?.printPdf) {
      const errorMsg = "打印功能不可用，请在 Electron 环境中运行";
      window.electronAPI?.log("error", errorMsg);
      alert(errorMsg);
      return;
    }

    if (printers.length > 0 && !selectedPrinter) {
      alert("请先选择打印机");
      return;
    }

    if (pdfFiles.length === 0 && originPdfUrls.length === 0) {
      const errorMsg = "PDF 尚未加载完成，请稍候";
      window.electronAPI?.log("warn", errorMsg);
      alert(errorMsg);
      return;
    }

    setIsPrinting(true);
    try {
      // 优先使用已加载的 base64 数据，确保数据完整
      let printData: string;
      let dataType: string;

      if (pdfFiles[0] && pdfFiles[0].startsWith("data:application/pdf;base64,")) {
        printData = pdfFiles[0];
        dataType = "base64数据";

        // 验证 base64 数据长度（至少应该有几KB）
        const base64Part = printData.replace("data:application/pdf;base64,", "");
        const estimatedSize = (base64Part.length * 3) / 4;
        window.electronAPI.log("info", `使用base64数据打印，估算大小: ${Math.round(estimatedSize)} bytes`);

        if (estimatedSize < 1024) {
          window.electronAPI.log("warn", "base64数据可能不完整，尝试使用原始URL");
          // 如果base64数据太小，回退到URL
          if (originPdfUrls[0]) {
            printData = originPdfUrls[0];
            dataType = "远程文件路径";
          }
        }
      } else if (originPdfUrls[0]) {
        printData = originPdfUrls[0];
        dataType = "远程文件路径";
      } else {
        throw new Error("没有可用的PDF数据");
      }

      window.electronAPI.log("info", `开始打印PDF (${dataType}): ${dataType === "base64数据" ? `base64长度${printData.length}` : printData.substring(0, 100)}...`);

      const printResult = await window.electronAPI.printPdf(
        printData,
        {
          ...(selectedPrinter ? { printerName: selectedPrinter } : {}),
          duplex: duplexEnabled,
        }
      );

      if (!printResult.success) {
        const errorMsg = `打印失败: ${printResult.error || "未知错误"}`;
        window.electronAPI.log("error", errorMsg);
        alert(errorMsg);
        return;
      }

      window.electronAPI.log("info", "PDF打印请求已发送成功");
      navigate("/UI81");
    } catch (error) {
      const errorMsg = `打印错误: ${(error as Error).message || error}`;
      console.error(errorMsg);
      window.electronAPI.log("error", errorMsg);
      alert("打印失败，请重试");
    } finally {
      setIsPrinting(false);
    }
  }, [originPdfUrls, pdfFiles, printers.length, selectedPrinter, navigate, isPrinting, duplexEnabled]);

  const handlePageCountUpdate = useCallback((index: number, numPages: number) => {
    window.electronAPI?.log("info", `[UI8] PDF渲染成功 (index=${index})，共 ${numPages} 页`);
    setPageCounts((prev) => {
      if (prev[index] === numPages) return prev;
      return { ...prev, [index]: numPages };
    });
    setLoading(false);
    setError("");
  }, []);

  const onDocumentLoadError = useCallback((error: Error) => {
    const errorMsg = `PDF渲染失败: ${error.message || error}`;
    console.error("PDF load error:", error);
    window.electronAPI?.log("error", errorMsg);
    setError("PDF 加载失败，请检查网络连接");
    setLoading(false);
  }, []);

  return (
    <div className="basic-root">
      <div className="ui8-printer-panel" ref={printerDropdownRef}>
        <div
          className={`ui8-printer-trigger ${printersLoading || printers.length === 0 ? "disabled" : ""
            } ${isPrinterDropdownOpen ? "open" : ""}`}
          role="button"
          tabIndex={0}
          onClick={togglePrinterDropdown}
          onKeyDown={(event) => {
            if (event.key === "Enter" || event.key === " ") {
              event.preventDefault();
              togglePrinterDropdown();
            }
          }}
        >
          <DuplexToggle
            checked={duplexEnabled}
            onChange={(enabled) => {
              setDuplexEnabled(enabled);
              localStorage.setItem(PREFERRED_DUPLEX_KEY, enabled.toString());
              window.electronAPI?.log(
                "info",
                `[UI8] 双面打印设置为: ${enabled ? "启用" : "禁用"}`
              );
            }}
          />
          <span>
            {printersLoading
              ? "打印机加载中..."
              : selectedPrinter
                ? printers.find((p) => p.name === selectedPrinter)?.displayName ||
                selectedPrinter
                : printers.length === 0
                  ? "未检测到打印机"
                  : "请选择打印机"}
          </span>
          <span className="ui8-printer-arrow" />
        </div>
        {isPrinterDropdownOpen && printers.length > 0 && (
          <div className="ui8-printer-options">
            {printers.map((printer) => (
              <div
                key={printer.name}
                className={`ui8-printer-option ${printer.name === selectedPrinter ? "active" : ""
                  }`}
                onClick={() => handlePrinterChange(printer.name)}
                role="button"
                tabIndex={0}
                onKeyDown={(event) => {
                  if (event.key === "Enter" || event.key === " ") {
                    event.preventDefault();
                    handlePrinterChange(printer.name);
                  }
                }}
              >
                {printer.displayName || printer.name}
              </div>
            ))}
          </div>
        )}
        {printerError && (
          <div className="ui8-printer-error">{printerError}</div>
        )}

      </div>

      <div className="basic-white-block">
        <div className="basic-content">
          <div
            className="ui8-pdf-container"
            ref={pdfContainerRef}
            onScroll={handlePdfScroll}
          >
            <PdfRenderer
              pdfFiles={pdfFiles}
              loading={loading}
              error={error}
              pageCounts={pageCounts}
              onPageCountUpdate={handlePageCountUpdate}
              onDocumentLoadError={onDocumentLoadError}
            />
          </div>

          <div
            className={`ui8-right-section${isRightSectionHidden ? " ui8-right-section--hidden" : ""
              }`}
          >
            <img src={ui8A} alt="" />
            <img src={ui8B} alt="" />
          </div>

          <div className="">
            {/* <BackButton text="返回" onClick={handleBack} /> */}
            <ConfirmButton
              text={isPrinting ? "打印中..." : "打印导检单"}
              onClick={handleConfirm}
              disabled={isPrinting}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default UI8;
