import React, { useState, useEffect, useCallback } 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 BackButton from "../../components/BackButton";
import ConfirmButton from "../../components/ConfirmButton";
import ui8A from "../../assets/ui8A.png";
import ui8B from "../../assets/ui8B.png";
import { getDaojiandanPdf } from "../../api/hisApi";

// 独立的 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 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();
        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失败");
        }

        const 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();
  }, []);

  const handleBack = useCallback(() => {
    navigate(-1);
  }, [navigate]);

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

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

    setIsPrinting(true);
    try {
      const printData =
        primaryPdf.startsWith("data:") && pdfFiles[0]
          ? primaryPdf
          : originPdfUrls[0];
      const dataType = printData.startsWith("data:") ? "base64数据" : "远程文件路径";
      window.electronAPI.log("info", `开始打印PDF (${dataType}): ${printData.substring(0, 100)}...`);
      
      const result = await window.electronAPI.printPdf(printData);
      if (!result.success) {
        const errorMsg = `打印失败: ${result.error || "未知错误"}`;
        window.electronAPI.log("error", errorMsg);
        alert(errorMsg);
      } else {
        window.electronAPI.log("info", "PDF打印请求已发送");
      }
    } catch (error) {
      const errorMsg = `Print error: ${error}`;
      console.error(errorMsg);
      window.electronAPI.log("error", errorMsg);
      alert("打印失败，请重试");
    } finally {
      setIsPrinting(false);
      navigate("/UI9");
    }
  }, [originPdfUrls, pdfFiles]);

  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="basic-white-block">
        <div className="basic-content">
          <div className="ui8-pdf-container">
            <PdfRenderer
              pdfFiles={pdfFiles}
              loading={loading}
              error={error}
              pageCounts={pageCounts}
              onPageCountUpdate={handlePageCountUpdate}
              onDocumentLoadError={onDocumentLoadError}
            />
          </div>

          <div className="ui8-right-section">
              <img src={ui8A} alt="" />
              <img src={ui8B} alt="" />
          </div>

          <div className="basic-confirm-section">
            <BackButton text="返回" onClick={handleBack} />
            <ConfirmButton 
              text={isPrinting ? "打印中..." : "打印"} 
              onClick={handleConfirm}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default UI8;
