'use client';

import { useState, useEffect } from 'react';
import { X, Download, Upload, AlertCircle, CheckCircle2, XCircle } from 'lucide-react';
import { toast } from '@/lib/toast';
import { batchImportUserMemberships, ImportUserMembershipDto, getOrganizations, type Organization } from '@/services/api/organization';
import { useTranslation } from '@/hooks/useTranslation';
import * as XLSX from 'xlsx';
import { brand } from '@/lib/brand';

interface BatchImportUserMembershipsDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  currentOrganizationId?: string; // ✅ 组织ID
}

interface ParsedMembership {
  email: string;
  departmentCode: string;
  positionId?: string;
  managerEmail?: string;
  title?: string;
  isPrimary?: boolean | string;
  error?: string;
}

export default function BatchImportUserMembershipsDialog({
  isOpen,
  onClose,
  onSuccess,
  currentOrganizationId,
}: BatchImportUserMembershipsDialogProps) {
  const { t } = useTranslation();
  const i18n = t.batchImportUserMemberships; // 批量导入用户成员关系专用翻译
  const [file, setFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [parseResult, setParseResult] = useState<{
    valid: ParsedMembership[];
    invalid: ParsedMembership[];
  } | null>(null);
  
  // ✅ 组织选择器状态
  const [organizations, setOrganizations] = useState<Organization[]>([]);
  const [selectedOrgId, setSelectedOrgId] = useState<string | null>(null);
  const [loadingOrgs, setLoadingOrgs] = useState(false);

  // ✅ 加载组织列表（仅在未传入 currentOrganizationId 时）
  useEffect(() => {
    if (isOpen && !currentOrganizationId) {
      loadOrganizations();
    } else if (isOpen && currentOrganizationId) {
      // 如果传入了组织ID，直接使用
      setSelectedOrgId(currentOrganizationId);
    }
  }, [isOpen, currentOrganizationId]);

  const loadOrganizations = async () => {
    try {
      setLoadingOrgs(true);
      const response = await getOrganizations();
      const orgs = response.items || []; // ✅ 从 response.items 获取数组
      setOrganizations(orgs);
      
      // 如果只有一个组织，自动选中
      if (orgs.length === 1) {
        setSelectedOrgId(orgs[0].id);
      }
    } catch (error) {
      console.error('Failed to load organizations:', error);
      toast.error('加载组织列表失败');
    } finally {
      setLoadingOrgs(false);
    }
  };

  if (!isOpen) return null;

  // 下载模板
  const handleDownloadTemplate = () => {
    // 创建模板数据
    const templateData = [
      {
        [i18n.template.fields.email + ' *']: `zhang.employee@${brand.sampleEmailDomain}`,
        [i18n.template.fields.departmentCode + ' *']: 'TECH',
        [i18n.template.fields.positionId]: '',
        [i18n.template.fields.managerEmail]: `wang.manager@${brand.sampleEmailDomain}`,
        [i18n.template.fields.title]: '高级工程师',
        [i18n.template.fields.isPrimary]: 'true',
      },
      {
        [i18n.template.fields.email + ' *']: `li.employee@${brand.sampleEmailDomain}`,
        [i18n.template.fields.departmentCode + ' *']: 'TECH-FE',
        [i18n.template.fields.positionId]: '',
        [i18n.template.fields.managerEmail]: `zhang.leader@${brand.sampleEmailDomain}`,
        [i18n.template.fields.title]: '前端开发工程师',
        [i18n.template.fields.isPrimary]: 'false',
      },
      {
        [i18n.template.fields.email + ' *']: `wang.employee@${brand.sampleEmailDomain}`,
        [i18n.template.fields.departmentCode + ' *']: 'TECH-BE',
        [i18n.template.fields.positionId]: '',
        [i18n.template.fields.managerEmail]: `liu.manager@${brand.sampleEmailDomain}`,
        [i18n.template.fields.title]: '后端开发工程师',
        [i18n.template.fields.isPrimary]: 'true',
      },
    ];

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

    // 设置列宽
    ws['!cols'] = [
      { wch: 30 }, // 用户邮箱
      { wch: 20 }, // 部门编码
      { wch: 40 }, // 岗位ID
      { wch: 30 }, // 直属主管邮箱
      { wch: 20 }, // 部门内头衔
      { wch: 15 }, // 是否主部门
    ];

    XLSX.utils.book_append_sheet(wb, ws, '成员关系导入模板');

    // 下载文件
    XLSX.writeFile(wb, '批量导入成员关系模板.xlsx');
    toast.success(i18n.template.downloaded);
  };

  // 邮箱格式验证
  const isValidEmail = (email: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  // 解析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: 'binary' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet) as any[];

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

        jsonData.forEach((row, index) => {
          const emailKey = i18n.template.fields.email + ' *';
          const deptCodeKey = i18n.template.fields.departmentCode + ' *';
          
          const membership: ParsedMembership = {
            email: row[emailKey] || row[i18n.template.fields.email] || '',
            departmentCode: row[deptCodeKey] || row[i18n.template.fields.departmentCode] || '',
            positionId: row[i18n.template.fields.positionId] || undefined,
            managerEmail: row[i18n.template.fields.managerEmail] || undefined,
            title: row[i18n.template.fields.title] || undefined,
            isPrimary: row[i18n.template.fields.isPrimary] !== undefined 
              ? row[i18n.template.fields.isPrimary] 
              : undefined,
          };

          // 验证必填字段
          if (!membership.email || !membership.departmentCode) {
            membership.error = i18n.validation.errorReasons.missingRequired;
            invalid.push(membership);
          } else if (!isValidEmail(membership.email)) {
            membership.error = i18n.validation.errorReasons.invalidEmailFormat;
            invalid.push(membership);
          } else if (!/^[A-Z0-9_-]+$/.test(membership.departmentCode)) {
            membership.error = i18n.validation.errorReasons.invalidDepartmentCode;
            invalid.push(membership);
          } else {
            valid.push(membership);
          }
        });

        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.readAsBinaryString(selectedFile);
  };

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

    // ✅ 使用 selectedOrgId（可能来自传入的 currentOrganizationId 或用户选择）
    const organizationId = selectedOrgId;
    
    console.log('[BatchImportMemberships] organizationId:', organizationId);
    
    if (!organizationId) {
      toast.error('请选择目标组织');
      return;
    }

    setIsUploading(true);

    try {
      const users: ImportUserMembershipDto[] = parseResult.valid.map(m => ({
        email: m.email,
        departmentCode: m.departmentCode,
        organizationId, // ✅ 使用选中的组织ID
        positionId: m.positionId,
        managerEmail: m.managerEmail,
        title: m.title,
        isPrimary: m.isPrimary,
      }));

      const result = await batchImportUserMemberships({ users });
      
      // 🔍 调试：检查返回结果
      console.log('[BatchImportMemberships] API响应:', result);

      if (!result || !result.results) {
        throw new Error('导入API未返回结果');
      }

      // ✅ 从 results 对象中读取
      const successCount = result.results.success?.length || 0;
      const failedCount = result.results.failed?.length || 0;

      if (failedCount === 0) {
        toast.success(i18n.messages.importSuccess.replace('{count}', successCount.toString()));
        onSuccess();
        onClose();
      } else {
        toast.warning(i18n.messages.importPartial
          .replace('{success}', successCount.toString())
          .replace('{failed}', failedCount.toString()));
        
        // 更新解析结果，显示失败信息
        setParseResult({
          valid: parseResult.valid.filter(m => 
            !result.results.failed.some(f => f.email === m.email)
          ),
          invalid: [
            ...parseResult.invalid,
            ...result.results.failed.map(f => ({
              email: f.email,
              departmentCode: '',
              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-4xl 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)]">
          {/* ✅ 组织选择器（仅在未传入 currentOrganizationId 时显示） */}
          {!currentOrganizationId && (
            <div className="mb-6 p-4 bg-blue-50 rounded-lg border border-blue-200">
              <label className="block text-sm font-medium text-blue-900 mb-2">
                🏢 目标组织 *
              </label>
              {loadingOrgs ? (
                <div className="text-sm text-blue-700">加载组织列表...</div>
              ) : organizations.length === 0 ? (
                <div className="text-sm text-red-600">未找到可用组织，请联系管理员</div>
              ) : organizations.length === 1 ? (
                <div className="text-sm text-blue-900 font-medium">
                  {organizations[0].displayName || organizations[0].name} <span className="text-blue-600">(已自动选中)</span>
                </div>
              ) : (
                <select
                  value={selectedOrgId || ''}
                  onChange={(e) => setSelectedOrgId(e.target.value)}
                  className="w-full px-3 py-2 border border-blue-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  style={{ backgroundColor: 'white' }}
                >
                  <option value="">-- 请选择组织 --</option>
                  {organizations.map(org => (
                    <option key={org.id} value={org.id}>
                      {org.displayName || org.name}
                    </option>
                  ))}
                </select>
              )}
              <p className="text-xs text-blue-700 mt-2">
                💡 成员关系将导入到选定的组织
              </p>
            </div>
          )}

          {/* 步骤说明 */}
          <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 p-4 bg-amber-50 rounded-lg border border-amber-200">
            <div className="flex items-start gap-3">
              <AlertCircle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-amber-800">
                <p className="font-medium mb-1">⚠️ 重要说明</p>
                <p>{i18n.template.autoCodeTip}</p>
              </div>
            </div>
          </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.email} *</strong>：{i18n.template.fields.emailDesc}</p>
              <p><strong>{i18n.template.fields.departmentCode} *</strong>：{i18n.template.fields.departmentCodeDesc}</p>
              <p><strong>{i18n.template.fields.positionId}</strong>：{i18n.template.fields.positionIdDesc}</p>
              <p><strong>{i18n.template.fields.managerEmail}</strong>：{i18n.template.fields.managerEmailDesc}</p>
              <p><strong>{i18n.template.fields.title}</strong>：{i18n.template.fields.titleDesc}</p>
              <p><strong>{i18n.template.fields.isPrimary}</strong>：{i18n.template.fields.isPrimaryDesc}</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.email}</th>
                          <th className="px-2 py-1 text-left">{i18n.table.departmentCode}</th>
                          <th className="px-2 py-1 text-left">{i18n.table.managerEmail}</th>
                          <th className="px-2 py-1 text-left">{i18n.table.title}</th>
                          <th className="px-2 py-1 text-center">{i18n.table.isPrimary}</th>
                        </tr>
                      </thead>
                      <tbody className="text-gray-700">
                        {parseResult.valid.map((membership, idx) => (
                          <tr key={idx} className="border-t border-gray-100">
                            <td className="px-2 py-1 text-xs">{membership.email}</td>
                            <td className="px-2 py-1 font-mono text-xs">{membership.departmentCode}</td>
                            <td className="px-2 py-1 text-xs">{membership.managerEmail || i18n.table.empty}</td>
                            <td className="px-2 py-1 text-xs">{membership.title || i18n.table.empty}</td>
                            <td className="px-2 py-1 text-center text-xs">
                              {membership.isPrimary === 'true' || membership.isPrimary === true 
                                ? i18n.table.yes 
                                : membership.isPrimary === 'false' || membership.isPrimary === false
                                ? i18n.table.no
                                : i18n.table.empty}
                            </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.email}</th>
                          <th className="px-2 py-1 text-left">{i18n.table.departmentCode}</th>
                          <th className="px-2 py-1 text-left">{i18n.table.error}</th>
                        </tr>
                      </thead>
                      <tbody className="text-gray-700">
                        {parseResult.invalid.map((membership, idx) => (
                          <tr key={idx} className="border-t border-gray-100">
                            <td className="px-2 py-1 text-xs">{membership.email || i18n.table.empty}</td>
                            <td className="px-2 py-1 font-mono text-xs">{membership.departmentCode || i18n.table.empty}</td>
                            <td className="px-2 py-1 text-red-600 text-xs">{membership.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>
  );
}


