import React, { useState, useMemo, useEffect } from 'react';
import { Select, Button, Space, message } from 'antd';
import { showNotImplemented } from '@/utils/notificationHelper';
import { useAppSelector } from '@/states/store';
import { getPrintManager } from '@/services/print';
import { selectFilmHasImage } from '@/states/print/selectors';
import { useSelector } from 'react-redux';

const PrintControl: React.FC = () => {
  const [selectedNode, setSelectedNode] = useState<string>('');
  const [selectedSize, setSelectedSize] = useState<string>('14IN×17IN');
  const [isPrinting, setIsPrinting] = useState(false);
  const [canPrint, setCanPrint] = useState<boolean>(false);

  // 获取当前胶片信息
  const activeFilm = useAppSelector((state) => {
    const films = state.print.films;
    const activeId = state.print.activeFilmId;
    return films.find(f => f.id === activeId);
  });
  const hasImage = useSelector(() => selectFilmHasImage(activeFilm));
  // 创建打印管理器实例
  const printManager = useMemo(() => getPrintManager(), []);

  // TODO: 打印节点需要从后端API获取
  const printNodes = [
    { value: 'node1', label: 'TestPrinter' },
    // { value: 'node2', label: '打印节点2' },
  ];
  // 检查当前胶片是否有图像
  const checkIfCanPrint = () => {
    if (activeFilm && hasImage) {
      setCanPrint(true);
    } else {
      setCanPrint(false);
    }
  };

  useEffect(() => {
    checkIfCanPrint();
  }, [activeFilm, activeFilm?.images]);

  const handleLocalPrint = async () => {
    if (isPrinting) {
      message.warning('打印正在进行中，请稍候');
      return;
    }

    if (!canPrint) {
      message.warning('当前胶片上没有图像，无法打印');
      return;
    }

    try {
      setIsPrinting(true);

      console.log('[本地打印] 开始打印，胶片尺寸:', selectedSize);

      // 调试：检查 Electron 环境
      console.log('[本地打印] 检查 window.electronPrint:', !!window.electronPrint);
      console.log('[本地打印] 检查 window.electronAPI:', !!window.electronAPI);

      // 检查胶片元素是否存在
      const filmElement = document.getElementById('film-print-area');
      if (!filmElement) {
        throw new Error('未找到胶片元素 film-print-area');
      }

      // 检查Canvas数量
      const canvases = filmElement.querySelectorAll('canvas');
      console.log(`[本地打印] 发现 ${canvases.length} 个Canvas元素`);

      await printManager.print({
        elementId: 'film-print-area',
        filmSize: selectedSize,
        orientation: activeFilm?.orientation === 'horizontal' ? 'landscape' : 'portrait',
        silent: false, // 显示打印对话框，让用户选择打印机
      });

      message.info('打印结束');
    } catch (error) {
      console.error('[本地打印] 打印失败:', error);
      message.error(`打印失败: ${error.message || '未知错误'}`);
    } finally {
      setIsPrinting(false);
    }
  };

  const handleDicomPrint = () => {
    showNotImplemented('DICOM打印');
  };
  const filmSizes = [
    { value: '14IN×17IN', label: '14IN×17IN' },
    { value: '14IN×14IN', label: '14IN×14IN' },
    { value: '17IN×17IN', label: '17IN×17IN' },
  ];
  useEffect(() => {
    checkIfCanPrint();
  }, [activeFilm]);

  return (
    <div>
      <div className="font-semibold">打印设置</div>
      <Space direction="vertical" style={{ width: '100%' }} size="middle">
        {/* 打印节点下拉框 */}
        <div>
          <div className="mb-1">打印节点</div>
          <Select
            style={{ width: '100%' }}
            placeholder="选择打印节点"
            value={selectedNode}
            onChange={setSelectedNode}
            options={printNodes}
            // TODO: 暂时disabled，等待后端API
            disabled={printNodes.length === 0}
          />
          {printNodes.length === 0 && (
            <div className="text-gray-400 mt-1">
              TODO: 等待后端API提供打印节点
            </div>
          )}
        </div>

        {/* 尺寸下拉框 */}
        <div>
          <div className="mb-1">胶片尺寸</div>
          <Select
            style={{ width: '100%' }}
            value={selectedSize}
            onChange={setSelectedSize}
            options={filmSizes}
          />
        </div>

        {/* 打印按钮 */}
        <div>
          <Space direction="vertical" style={{ width: '100%' }}>
            <Button
              type="primary"
              block
              onClick={handleLocalPrint}
              disabled={!canPrint}
            >
              本地打印
            </Button>
            <Button
              block
              onClick={handleDicomPrint}
              disabled={!selectedNode}
            >
              DICOM打印
            </Button>
          </Space>
        </div>
      </Space>
    </div>
  );
};

export default PrintControl;
