'use client';

import { useState } from 'react';
import { X, Download, Upload, AlertCircle, CheckCircle2, XCircle } from 'lucide-react';
import { toast } from '@/lib/toast';
import { batchCreateDepartments, CreateDepartmentDto } from '@/services/api/organization';
import { useTranslation } from '@/hooks/useTranslation';
import * as XLSX from 'xlsx';

interface BatchImportDepartmentsDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  currentOrganizationId?: string; // 组织ID（必需）
  rootDepartmentId?: string | null; // 根部门ID，用作parentId
}

interface ParsedDepartment {
  name: string;
  code: string;
  parentCode?: string;
  description?: string;
  order?: number;
  error?: string;
}

export default function BatchImportDepartmentsDialog({
  isOpen,
  onClose,
  onSuccess,
  currentOrganizationId,
  rootDepartmentId,
}: BatchImportDepartmentsDialogProps) {
  const { t } = useTranslation();
  const i18n = t.batchImportDept; // 批量导入专用翻译
  const [file, setFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [parseResult, setParseResult] = useState<{
    valid: ParsedDepartment[];
    invalid: ParsedDepartment[];
  } | null>(null);

  if (!isOpen) return null;

  // 下载模板
  const handleDownloadTemplate = () => {
    // 创建模板数据
    const templateData = [
      {
        [i18n.template.fields.name + ' *']: '技术部',
        [i18n.template.fields.code + ' *']: 'TECH',
        [i18n.template.fields.parentCode]: '',
        [i18n.template.fields.description]: '技术研发部门',
        [i18n.template.fields.order]: 1,
      },
      {
        [i18n.template.fields.name + ' *']: '前端组',
        [i18n.template.fields.code + ' *']: 'TECH-FE',
        [i18n.template.fields.parentCode]: 'TECH',
        [i18n.template.fields.description]: '前端开发组',
        [i18n.template.fields.order]: 1,
      },
      {
        [i18n.template.fields.name + ' *']: '后端组',
        [i18n.template.fields.code + ' *']: 'TECH-BE',
        [i18n.template.fields.parentCode]: 'TECH',
        [i18n.template.fields.description]: '后端开发组',
        [i18n.template.fields.order]: 2,
      },
    ];

    // 创建工作簿
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet(templateData);

    // 设置列宽
    ws['!cols'] = [
      { wch: 20 }, // 部门名称
      { wch: 20 }, // 部门编码
      { wch: 20 }, // 上级部门编码
      { wch: 30 }, // 描述
      { wch: 10 }, // 排序
    ];

    XLSX.utils.book_append_sheet(wb, ws, '部门导入模板');

    // 下载文件
    XLSX.writeFile(wb, '批量创建部门模板.xlsx');
    toast.success(i18n.template.downloaded);
  };

  // 解析Excel文件
  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    if (!selectedFile) return;

    setFile(selectedFile);

    // 读取并解析文件
    const reader = new FileReader();
    reader.onload = (event) => {
      try {
        const data = event.target?.result;
        const workbook = XLSX.read(data, { type: 'array' }); // 🔧 使用 'array' 支持中文
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet) as any[];

        // 解析数据
        const valid: ParsedDepartment[] = [];
        const invalid: ParsedDepartment[] = [];

        // 🔧 第一遍：收集所有部门编码（用于验证同批次的父部门引用）
        const allCodesInBatch = new Set<string>();
        jsonData.forEach((row) => {
          const codeKey = i18n.template.fields.code + ' *';
          const code = row[codeKey] || row[i18n.template.fields.code] || '';
          if (code) {
            allCodesInBatch.add(code.trim());
          }
        });

        // 🔧 第二遍：验证每一行
        jsonData.forEach((row, index) => {
          const nameKey = i18n.template.fields.name + ' *';
          const codeKey = i18n.template.fields.code + ' *';
          
          const dept: ParsedDepartment = {
            name: row[nameKey] || row[i18n.template.fields.name] || '',
            code: row[codeKey] || row[i18n.template.fields.code] || '',
            parentCode: row[i18n.template.fields.parentCode] || undefined,
            description: row[i18n.template.fields.description] || undefined,
            order: row[i18n.template.fields.order] ? Number(row[i18n.template.fields.order]) : undefined,
          };

          // 验证必填字段
          if (!dept.name || !dept.code) {
            dept.error = i18n.validation.errorReasons.missingRequired;
            invalid.push(dept);
          } else if (!/^[A-Z0-9_-]+$/.test(dept.code)) {
            dept.error = i18n.validation.errorReasons.invalidCodeFormat;
            invalid.push(dept);
          } else if (dept.parentCode && !allCodesInBatch.has(dept.parentCode)) {
            // 🔧 只有当父编码不在同批次中时，才标记为潜在错误（提交时会再次验证数据库）
            // 这里只是警告，不阻止导入
            dept.error = i18n.validation.errorReasons.parentNotFound.replace('{code}', dept.parentCode);
            invalid.push(dept);
          } else {
            valid.push(dept);
          }
        });

        setParseResult({ valid, invalid });

        if (invalid.length > 0) {
          toast.warning(i18n.upload.parseWarning.replace('{count}', invalid.length.toString()));
        } else {
          toast.success(i18n.upload.parseSuccess.replace('{count}', valid.length.toString()));
        }
      } catch (error) {
        console.error('解析文件失败:', error);
        toast.error(i18n.upload.parseFailed);
      }
    };
    reader.readAsArrayBuffer(selectedFile); // 🔧 使用 ArrayBuffer 支持中文和所有编码
  };

  // 提交导入
  const handleSubmit = async () => {
    if (!parseResult || parseResult.valid.length === 0) {
      toast.error(i18n.messages.noValidData);
      return;
    }

    // 🔍 调试：检查组织ID和根部门ID
    console.log('[BatchImport] currentOrganizationId:', currentOrganizationId);
    console.log('[BatchImport] rootDepartmentId:', rootDepartmentId);
    
    if (!currentOrganizationId) {
      toast.error('未获取到当前组织ID，请刷新页面重试');
      return;
    }
    
    if (!rootDepartmentId) {
      toast.error('未获取到根部门ID，请刷新页面重试');
      return;
    }

    setIsUploading(true);

    try {
      // 构建部门编码映射（用于解析父部门）
      const codeToIdMap = new Map<string, string>();
      
      // 第一步：创建所有顶级部门（没有父部门编码的）
      const topLevelDepts = parseResult.valid.filter(d => !d.parentCode);
      const childDepts = parseResult.valid.filter(d => d.parentCode);

      // 创建顶级部门
      if (topLevelDepts.length > 0) {
        const topLevelDtos: CreateDepartmentDto[] = topLevelDepts.map(dept => ({
          organizationId: currentOrganizationId, // ✅ 组织ID（后端必填）
          name: dept.name,
          code: dept.code,
          parentId: rootDepartmentId, // ✅ 父部门ID（根部门）
          description: dept.description,
          order: dept.order,
        }));

        console.log('[BatchImport] 创建顶级部门:', topLevelDtos);
        const topResult = await batchCreateDepartments(topLevelDtos);
        console.log('[BatchImport] 顶级部门创建结果:', topResult);
        
        // 记录成功创建的部门
        topResult.results.success.forEach(s => {
          codeToIdMap.set(s.code, s.id);
        });
      }

      // 第二步：创建子部门（需要解析父部门）
      let childResult: any = { successCount: 0, failedCount: 0, results: { success: [], failed: [] } };
      
      if (childDepts.length > 0) {
        const childDtos: CreateDepartmentDto[] = [];
        const failedChildren: ParsedDepartment[] = [];

        childDepts.forEach(dept => {
          const parentId = codeToIdMap.get(dept.parentCode!);
          if (parentId) {
            childDtos.push({
              organizationId: currentOrganizationId, // ✅ 组织ID（后端必填）
              name: dept.name,
              code: dept.code,
              parentId,
              description: dept.description,
              order: dept.order,
            });
          } else {
            failedChildren.push({
              ...dept,
              error: i18n.validation.errorReasons.parentNotFound.replace('{code}', dept.parentCode!),
            });
          }
        });

        if (childDtos.length > 0) {
          childResult = await batchCreateDepartments(childDtos);
        }

        // 添加父部门不存在的失败记录
        childResult.results.failed.push(...failedChildren.map(d => ({
          code: d.code,
          name: d.name,
          error: d.error!,
        })));
        childResult.failedCount += failedChildren.length;
      }

      // 汇总结果
      const totalSuccess = (topLevelDepts.length - 0) + childResult.successCount;
      const totalFailed = childResult.failedCount;

      if (totalFailed === 0) {
        toast.success(i18n.messages.importSuccess.replace('{count}', totalSuccess.toString()));
        onSuccess();
        onClose();
      } else {
        toast.warning(i18n.messages.importPartial
          .replace('{success}', totalSuccess.toString())
          .replace('{failed}', totalFailed.toString()));
        // 更新解析结果，显示失败信息
        setParseResult({
          valid: parseResult.valid.filter(d => 
            !childResult.results.failed.some((f: any) => f.code === d.code)
          ),
          invalid: [
            ...parseResult.invalid,
            ...childResult.results.failed.map((f: any) => ({
              name: f.name,
              code: f.code,
              error: f.error,
            })),
          ],
        });
      }
    } catch (error: any) {
      console.error('批量导入失败:', error);
      toast.error(error.message || i18n.messages.importFailed);
    } finally {
      setIsUploading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* 背景遮罩 */}
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />

      {/* 对话框 */}
      <div className="relative bg-white rounded-xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-hidden">
        {/* 头部 */}
        <div className="flex items-center justify-between px-6 py-4 border-b" style={{ borderColor: '#e5e6eb' }}>
          <h2 className="text-lg font-semibold text-gray-900">{i18n.title}</h2>
          <button
            onClick={onClose}
            className="p-1 rounded-lg hover:bg-gray-100 transition-colors"
          >
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {/* 内容 */}
        <div className="p-6 overflow-y-auto max-h-[calc(90vh-140px)]">
          {/* 步骤说明 */}
          <div className="mb-6 p-4 bg-blue-50 rounded-lg border border-blue-200">
            <h3 className="text-sm font-medium text-blue-900 mb-2">📋 {i18n.steps.title}</h3>
            <ol className="text-sm text-blue-800 space-y-1 list-decimal list-inside">
              <li>{i18n.steps.step1}</li>
              <li>{i18n.steps.step2}</li>
              <li>{i18n.steps.step3}</li>
              <li>{i18n.steps.step4}</li>
            </ol>
          </div>

          {/* 模板说明 */}
          <div className="mb-6">
            <h3 className="text-sm font-medium text-gray-900 mb-3">📝 {i18n.template.title}</h3>
            <div className="bg-gray-50 rounded-lg p-4 text-sm text-gray-700 space-y-2">
              <p><strong>{i18n.template.fields.name} *</strong>：{i18n.template.fields.nameDesc}</p>
              <p><strong>{i18n.template.fields.code} *</strong>：{i18n.template.fields.codeDesc}</p>
              <p><strong>{i18n.template.fields.parentCode}</strong>：{i18n.template.fields.parentCodeDesc}</p>
              <p><strong>{i18n.template.fields.description}</strong>：{i18n.template.fields.descriptionDesc}</p>
              <p><strong>{i18n.template.fields.order}</strong>：{i18n.template.fields.orderDesc}</p>
              <p className="text-xs text-gray-500 mt-2">{i18n.template.autoCodeTip}</p>
            </div>
          </div>

          {/* 下载模板按钮 */}
          <div className="mb-6">
            <button
              onClick={handleDownloadTemplate}
              className="w-full h-12 px-4 rounded-lg text-sm font-medium transition-all hover:shadow-md flex items-center justify-center gap-2"
              style={{ 
                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                color: 'white',
              }}
            >
              <Download className="w-5 h-5" />
              <span>{i18n.template.downloadBtn}</span>
            </button>
          </div>

          {/* 文件上传 */}
          <div className="mb-6">
            <label className="block text-sm font-medium text-gray-700 mb-2">
              {i18n.upload.title}
            </label>
            <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-500 transition-colors">
              <input
                type="file"
                accept=".xlsx,.xls"
                onChange={handleFileChange}
                className="hidden"
                id="file-upload"
              />
              <label htmlFor="file-upload" className="cursor-pointer">
                <Upload className="w-12 h-12 text-gray-400 mx-auto mb-3" />
                <p className="text-sm text-gray-600 mb-1">
                  {file ? file.name : i18n.upload.placeholder}
                </p>
                <p className="text-xs text-gray-500">
                  {i18n.upload.formatHint}
                </p>
              </label>
            </div>
          </div>

          {/* 解析结果 */}
          {parseResult && (
            <div className="space-y-4">
              {/* 有效数据 */}
              {parseResult.valid.length > 0 && (
                <div className="border border-green-200 rounded-lg overflow-hidden">
                  <div className="bg-green-50 px-4 py-2 flex items-center gap-2">
                    <CheckCircle2 className="w-4 h-4 text-green-600" />
                    <span className="text-sm font-medium text-green-900">
                      {i18n.validation.validData} ({i18n.validation.dataCount.replace('{count}', parseResult.valid.length.toString())})
                    </span>
                  </div>
                  <div className="p-4 max-h-48 overflow-y-auto">
                    <table className="w-full text-sm">
                      <thead className="text-xs text-gray-500 bg-gray-50">
                        <tr>
                          <th className="px-2 py-1 text-left">{i18n.table.deptName}</th>
                          <th className="px-2 py-1 text-left">{i18n.table.deptCode}</th>
                          <th className="px-2 py-1 text-left">{i18n.table.parentCode}</th>
                        </tr>
                      </thead>
                      <tbody className="text-gray-700">
                        {parseResult.valid.map((dept, idx) => (
                          <tr key={idx} className="border-t border-gray-100">
                            <td className="px-2 py-1">{dept.name}</td>
                            <td className="px-2 py-1 font-mono text-xs">{dept.code}</td>
                            <td className="px-2 py-1 font-mono text-xs">{dept.parentCode || i18n.table.noParent}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              )}

              {/* 无效数据 */}
              {parseResult.invalid.length > 0 && (
                <div className="border border-red-200 rounded-lg overflow-hidden">
                  <div className="bg-red-50 px-4 py-2 flex items-center gap-2">
                    <XCircle className="w-4 h-4 text-red-600" />
                    <span className="text-sm font-medium text-red-900">
                      {i18n.validation.invalidData} ({i18n.validation.dataCount.replace('{count}', parseResult.invalid.length.toString())})
                    </span>
                  </div>
                  <div className="p-4 max-h-48 overflow-y-auto">
                    <table className="w-full text-sm">
                      <thead className="text-xs text-gray-500 bg-gray-50">
                        <tr>
                          <th className="px-2 py-1 text-left">{i18n.table.deptName}</th>
                          <th className="px-2 py-1 text-left">{i18n.table.deptCode}</th>
                          <th className="px-2 py-1 text-left">{i18n.table.error}</th>
                        </tr>
                      </thead>
                      <tbody className="text-gray-700">
                        {parseResult.invalid.map((dept, idx) => (
                          <tr key={idx} className="border-t border-gray-100">
                            <td className="px-2 py-1">{dept.name || i18n.table.noParent}</td>
                            <td className="px-2 py-1 font-mono text-xs">{dept.code || i18n.table.noParent}</td>
                            <td className="px-2 py-1 text-red-600 text-xs">{dept.error}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* 底部按钮 */}
        <div className="flex items-center justify-end gap-3 px-6 py-4 border-t" style={{ borderColor: '#e5e6eb' }}>
          <button
            onClick={onClose}
            disabled={isUploading}
            className="px-4 py-2 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-100 transition-colors disabled:opacity-50"
          >
            {i18n.actions.cancel}
          </button>
          <button
            onClick={handleSubmit}
            disabled={!parseResult || parseResult.valid.length === 0 || isUploading}
            className="px-6 py-2 rounded-lg text-sm font-medium text-white transition-all hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed"
            style={{ 
              background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            }}
          >
            {isUploading ? i18n.actions.importing : i18n.actions.confirmWithCount.replace('{count}', (parseResult?.valid.length || 0).toString())}
          </button>
        </div>
      </div>
    </div>
  );
}
