/* === Data Import Page === */
function PageOperationDataImport() {
  const toast = useToast();
  const [templates, setTemplates] = React.useState([]);
  const [selectedTemplate, setSelectedTemplate] = React.useState("");
  const [dictCategories, setDictCategories] = React.useState([]);
  const [dictItems, setDictItems] = React.useState({});

  const [productCodeType, setProductCodeType] = React.useState('fixed');
  const [productCode, setProductCode] = React.useState("");
  const [productCodeDictCategory, setProductCodeDictCategory] = React.useState("");
  const [productCodeDictItem, setProductCodeDictItem] = React.useState("");
  const [productCodeGetValue, setProductCodeGetValue] = React.useState(false);

  const [productNameType, setProductNameType] = React.useState('fixed');
  const [productName, setProductName] = React.useState("");
  const [productNameDictCategory, setProductNameDictCategory] = React.useState("");
  const [productNameDictItem, setProductNameDictItem] = React.useState("");
  const [productNameGetValue, setProductNameGetValue] = React.useState(false);

  const [selectedFile, setSelectedFile] = React.useState(null);
  const [previewData, setPreviewData] = React.useState(null);
  const [previewTemplate, setPreviewTemplate] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [importing, setImporting] = React.useState(false);
  const [productCardExpanded, setProductCardExpanded] = React.useState(false);

  const API_BASE = window.API_BASE;

  React.useEffect(() => {
    fetchTemplates();
    fetchDictCategories();
  }, []);

  const fetchTemplates = async () => {
    try {
      const res = await fetch(`${API_BASE}/api/import/templates`);
      const json = await res.json();
      if (Array.isArray(json)) {
        setTemplates(json);
      } else if (json.data) {
        setTemplates(json.data);
      }
    } catch (err) {
      console.error('Failed to fetch templates:', err);
    }
  };

  const fetchDictCategories = async () => {
    try {
      const res = await fetch(`${API_BASE}/api/dict/category/tree`);
      const json = await res.json();
      if (Array.isArray(json)) {
        setDictCategories(json);
      }
    } catch (err) {
      console.error('Failed to fetch dict categories:', err);
    }
  };

  const flattenCategories = (nodes, level = 0, result = []) => {
    if (!Array.isArray(nodes)) return result;
    nodes.forEach(node => {
      result.push({
        code: node.code,
        name: node.name,
        level: level,
        indent: '　'.repeat(level)
      });
      if (node.children && node.children.length > 0) {
        flattenCategories(node.children, level + 1, result);
      }
    });
    return result;
  };

  const flatCategories = React.useMemo(() => {
    return flattenCategories(dictCategories);
  }, [dictCategories]);

  const fetchDictItems = async (categoryCode) => {
    if (dictItems[categoryCode]) return;
    try {
      const res = await fetch(`${API_BASE}/api/dict/item/select?category_code=${categoryCode}`);
      const json = await res.json();
      if (Array.isArray(json)) {
        setDictItems(prev => ({ ...prev, [categoryCode]: json }));
      }
    } catch (err) {
      console.error('Failed to fetch dict items:', err);
    }
  };

  const handleFileSelect = async (e) => {
    const file = e.target.files?.[0];
    if (!file || !selectedTemplate) return;

    setSelectedFile(file);
    setLoading(true);
    setPreviewData(null);

    const formData = new FormData();
    formData.append('template_code', selectedTemplate);
    formData.append('file', file);

    try {
      const res = await fetch(`${API_BASE}/api/import/preview`, {
        method: 'POST',
        body: formData
      });
      const json = await res.json();
      if (json.code === 200) {
        setPreviewData(json.data);
        // 保存模板信息用于渲染分组标题
        const templateInfo = templates.find(t => t.template_code === selectedTemplate);
        setPreviewTemplate(templateInfo || null);
      } else {
        toast.push('预览失败: ' + json.msg, 'error');
      }
    } catch (err) {
      console.error('Preview failed:', err);
      toast.push('预览失败', 'error');
    } finally {
      setLoading(false);
    }
  };

  const getProductCodeValue = () => {
    if (productCodeType === 'dict') {
      return productCodeGetValue ? productCodeDictItem : productCodeDictCategory;
    }
    return productCode;
  };

  const getProductNameValue = () => {
    if (productNameType === 'dict') {
      return productNameGetValue ? productNameDictItem : productNameDictCategory;
    }
    return productName;
  };

  const handleImport = async () => {
    if (!selectedFile) {
      toast.push('请选择文件', 'warn');
      return;
    }

    const codeValue = getProductCodeValue();
    const nameValue = getProductNameValue();

    setImporting(true);

    const formData = new FormData();
    formData.append('template_code', selectedTemplate);
    formData.append('product_code', codeValue);
    formData.append('product_name', nameValue);
    formData.append('file', selectedFile);

    try {
      const res = await fetch(`${API_BASE}/api/import/confirm`, {
        method: 'POST',
        body: formData
      });
      const json = await res.json();
      if (json.code === 200) {
        toast.push('导入成功！共导入 ' + json.data.imported_count + ' 条数据', 'success');
        setPreviewData(null);
        setSelectedFile(null);
      } else {
        toast.push('导入失败: ' + json.msg, 'error');
      }
    } catch (err) {
      console.error('Import failed:', err);
      toast.push('导入失败', 'error');
    } finally {
      setImporting(false);
    }
  };

  const handleCancel = () => {
    setPreviewData(null);
    setSelectedFile(null);
  };

  const selectedTemplateInfo = templates.find(t => t.template_code === selectedTemplate);

  return (
    <div className="page-import">
      <div className="import-config">
        <div className="form-row">
          <div className="form-group">
            <label>选择模板：</label>
            <select 
              value={selectedTemplate} 
              onChange={(e) => {
                setSelectedTemplate(e.target.value);
                setPreviewData(null);
                setSelectedFile(null);
              }}
              className="select"
            >
              <option value="">请选择模板</option>
              {templates.map(t => (
                <option key={t.template_code} value={t.template_code}>
                  {t.template_name} ({t.file_type_name || t.file_type})
                </option>
              ))}
            </select>
          </div>
        </div>

        {selectedTemplate && (
          <>
            {/* 可折叠的产品信息卡片 */}
            <div className="collapse-card">
              <div 
                className="collapse-card-header"
                onClick={() => setProductCardExpanded(!productCardExpanded)}
              >
                <span className="collapse-card-title">产品信息（可选）</span>
                <span className={`collapse-card-arrow ${productCardExpanded ? 'expanded' : ''}`}></span>
              </div>
              <div className={`collapse-card-content ${productCardExpanded ? 'expanded' : ''}`}>
                <div className="form-row">
                  <div className="form-group">
                    <label>产品编码：</label>
                    <div className="flex items-center gap-2">
                      <select
                        value={productCodeType}
                        onChange={(e) => {
                          setProductCodeType(e.target.value);
                          setProductCode('');
                          setProductCodeDictCategory('');
                          setProductCodeDictItem('');
                        }}
                        className="select"
                        style={{ width: '100px' }}
                      >
                        <option value="fixed">固定值</option>
                        <option value="dict">字典</option>
                      </select>
                      {productCodeType === 'fixed' && (
                        <input
                          type="text"
                          value={productCode}
                          onChange={(e) => setProductCode(e.target.value)}
                          className="input"
                          placeholder="请输入产品编码"
                        />
                      )}
                      {productCodeType === 'dict' && (
                        <>
                          <select
                            value={productCodeDictCategory}
                            onChange={(e) => {
                              setProductCodeDictCategory(e.target.value);
                              setProductCodeDictItem('');
                              fetchDictItems(e.target.value);
                            }}
                            className="select"
                            style={{ width: '140px' }}
                          >
                            <option value="">选择字典分类</option>
                            {flatCategories.map(cat => (
                              <option key={cat.code} value={cat.code}>{cat.indent}{cat.name}</option>
                            ))}
                          </select>
                          {productCodeDictCategory && dictItems[productCodeDictCategory] && (
                            <select
                              value={productCodeDictItem}
                              onChange={(e) => setProductCodeDictItem(e.target.value)}
                              className="select"
                              style={{ width: '140px' }}
                            >
                              <option value="">选择字典项</option>
                              {dictItems[productCodeDictCategory].map(item => (
                                <option key={item.value} value={item.value}>{item.label}</option>
                              ))}
                            </select>
                          )}
                          <label className="checkbox-label">
                            <input
                              type="checkbox"
                              checked={productCodeGetValue}
                              onChange={(e) => setProductCodeGetValue(e.target.checked)}
                            />
                            取值
                          </label>
                        </>
                      )}
                    </div>
                  </div>
                </div>

                <div className="form-row">
                  <div className="form-group">
                    <label>产品名称：</label>
                    <div className="flex items-center gap-2">
                      <select
                        value={productNameType}
                        onChange={(e) => {
                          setProductNameType(e.target.value);
                          setProductName('');
                          setProductNameDictCategory('');
                          setProductNameDictItem('');
                        }}
                        className="select"
                        style={{ width: '100px' }}
                      >
                        <option value="fixed">固定值</option>
                        <option value="dict">字典</option>
                      </select>
                      {productNameType === 'fixed' && (
                        <input
                          type="text"
                          value={productName}
                          onChange={(e) => setProductName(e.target.value)}
                          className="input"
                          placeholder="请输入产品名称"
                        />
                      )}
                      {productNameType === 'dict' && (
                        <>
                          <select
                            value={productNameDictCategory}
                            onChange={(e) => {
                              setProductNameDictCategory(e.target.value);
                              setProductNameDictItem('');
                              fetchDictItems(e.target.value);
                            }}
                            className="select"
                            style={{ width: '140px' }}
                          >
                            <option value="">选择字典分类</option>
                            {flatCategories.map(cat => (
                              <option key={cat.code} value={cat.code}>{cat.indent}{cat.name}</option>
                            ))}
                          </select>
                          {productNameDictCategory && dictItems[productNameDictCategory] && (
                            <select
                              value={productNameDictItem}
                              onChange={(e) => setProductNameDictItem(e.target.value)}
                              className="select"
                              style={{ width: '140px' }}
                            >
                              <option value="">选择字典项</option>
                              {dictItems[productNameDictCategory].map(item => (
                                <option key={item.value} value={item.value}>{item.label}</option>
                              ))}
                            </select>
                          )}
                          <label className="checkbox-label">
                            <input
                              type="checkbox"
                              checked={productNameGetValue}
                              onChange={(e) => setProductNameGetValue(e.target.checked)}
                            />
                            取值
                          </label>
                        </>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div className="form-group">
              <label>选择文件：</label>
              <div className="file-input-wrapper">
                <input 
                  type="file" 
                  className="file-input"
                  accept=".xlsx,.xls"
                  key={selectedFile ? 'file-input-' + Date.now() : 'file-input'}
                  onChange={handleFileSelect}
                />
                <div className={`file-input-visual ${selectedFile ? 'has-file' : ''}`}>
                  <div className="file-input-icon">
                    <svg viewBox="0 0 24 24">
                      <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8l-6-6z" />
                      <path d="M14 3.5L19.5 9H14z" fill="rgba(255,255,255,0.3)" />
                      <path d="M7 17h10M7 13h10M7 10h6" stroke="white" strokeWidth="1.5" strokeLinecap="round" />
                    </svg>
                  </div>
                  <div className="file-input-text">
                    <div className="file-input-title">
                      {selectedFile ? selectedFile.name : '点击或拖拽文件到这里'}
                    </div>
                    <div className="file-input-subtitle">
                      {selectedFile ? '已选择文件' : '支持 .xlsx, .xls 格式'}
                    </div>
                  </div>
                  <div className="file-input-btn">
                    {selectedFile ? '重新选择' : '选择文件'}
                  </div>
                </div>
              </div>
            </div>

            {selectedTemplateInfo && (
              <div className="template-info">
                <div className="info-item">
                  <span className="label">文件类型：</span>
                  <span className="value">{selectedTemplateInfo.file_type_name || selectedTemplateInfo.file_type}</span>
                </div>
                <div className="info-item">
                  <span className="label">列映射：</span>
                  <span className="value">
                    {selectedTemplateInfo.column_mapping?.map(m => m.field_name).join('、')}
                  </span>
                </div>
              </div>
            )}
          </>
        )}
      </div>

      {loading && (
        <div className="loading-area">
          <div className="loading-text">正在解析文件...</div>
        </div>
      )}

      {previewData && (
        <div className="preview-area">
          <div className="preview-header">
            <h3>数据预览</h3>
            <span className="total-count">共 {previewData.total} 条数据</span>
          </div>

          {/* 1. 原始数据 */}
          <div className="preview-section">
            <h4 className="preview-section-title">原始数据</h4>
            <div className="preview-table-wrap">
              <table className="preview-table">
                <thead>
                  <tr>
                    {previewData.raw_headers?.map((header, idx) => (
                      <th key={idx}>{header}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {previewData.raw_data?.slice(0, 10).map((row, rowIdx) => (
                    <tr key={rowIdx}>
                      {row.map((cell, colIdx) => (
                        <td key={colIdx}>{cell || '-'}</td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* 2. 解析预览 */}
          <div className="preview-section">
            <h4 className="preview-section-title">解析预览</h4>
            <div className="preview-table-wrap">
              <table className="preview-table-grouped">
                <thead>
                  <tr>
                    <th colSpan={Object.keys(previewData.parsed_data?.[0] || {}).filter(k => k !== 'group_name').length} key="header-all" className="group-header">
                      数据预览
                    </th>
                  </tr>
                  <tr>
                    {previewData.parsed_data?.[0] && Object.keys(previewData.parsed_data[0])
                      .filter(key => key !== 'group_name')
                      .map(key => {
                        // 判断是公共字段还是分组字段
                        const isCommon = previewTemplate?.common_mappings?.some(m => m.target_dict_item === key);
                        const groupIndex = previewTemplate?.groups?.findIndex(g => 
                          g.mappings?.some(m => m.target_dict_item === key)
                        );
                        let colClass = 'preview-col';
                        if (isCommon) {
                          colClass = 'common-col';
                        } else if (groupIndex >= 0) {
                          colClass = `group-col group-${groupIndex + 1}`;
                        }
                        return (
                          <th key={`th-${key}`} className={colClass}>
                            {previewData.parsed_data[0][key]?.field_name || key}
                          </th>
                        );
                      })}
                  </tr>
                </thead>
                <tbody>
                  {previewData.parsed_data?.slice(0, 10).map((row, idx) => (
                    <tr key={`row-${idx}`}>
                      {Object.keys(row)
                        .filter(key => key !== 'group_name')
                        .map(key => {
                          const isCommon = previewTemplate?.common_mappings?.some(m => m.target_dict_item === key);
                          const groupIndex = previewTemplate?.groups?.findIndex(g => 
                            g.mappings?.some(m => m.target_dict_item === key)
                          );
                          let colClass = 'preview-col';
                          if (isCommon) {
                            colClass = 'common-col';
                          } else if (groupIndex >= 0) {
                            colClass = `group-col group-${groupIndex + 1}`;
                          }
                          return (
                            <td key={`${idx}-${key}`} className={colClass}>
                              {row[key]?.value || '-'}
                            </td>
                          );
                        })}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* 3. SQL预览 */}
          <div className="preview-section">
            <h4 className="preview-section-title">SQL预览</h4>
            <div className="sql-preview-wrap">
              <textarea
                className="sql-preview"
                value={previewData.sql_preview?.slice(0, 10).join('\n\n') || ''}
                readOnly
              />
            </div>
          </div>

          {previewData.total > 10 && (
            <div className="preview-more">
              仅显示前10条，共 {previewData.total} 条数据
            </div>
          )}

          <div className="import-actions">
            <button 
              className="btn"
              onClick={handleCancel}
            >
              取消
            </button>
            <button 
              className="btn btn-primary"
              onClick={handleImport}
              disabled={importing}
            >
              {importing ? '导入中...' : '确认导入'}
            </button>
          </div>
        </div>
      )}

      {!selectedTemplate && (
        <div className="coming-soon">
          <div className="coming-soon-icon">📥</div>
          <h3>请选择导入模板</h3>
          <p>选择模板后上传 Excel 文件进行数据导入</p>
        </div>
      )}
    </div>
  );
}