'use client';

import React, { useState, useEffect } from 'react';
import { X, ChevronLeft, ChevronRight } from 'lucide-react';
import { useTranslation } from '@/hooks/useTranslation';
import { User } from '@/services/api/organization';
import { toast } from '@/lib/toast';
import UserAvatar from './UserAvatar';

interface UserDetailDrawerProps {
  userId: string | null;
  users?: User[]; // 用于 Previous/Next 导航
  onClose: () => void;
  onEdit?: (userId: string) => void;
  nested?: boolean; // 是否嵌套在其他抽屉/模态框中
}

type TabKey = 'basic' | 'job' | 'custom';

export default function UserDetailDrawer({ 
  userId, 
  users = [],
  onClose,
  onEdit,
  nested = false
}: UserDetailDrawerProps) {
  const { t } = useTranslation();
  const [activeTab, setActiveTab] = useState<TabKey>('basic');
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(false);

  // 当前用户在列表中的索引
  const currentIndex = users.findIndex(u => u.id === userId);
  const hasPrevious = currentIndex > 0;
  const hasNext = currentIndex >= 0 && currentIndex < users.length - 1;

  useEffect(() => {
    if (userId && users.length > 0) {
      loadUserDetail(userId);
    }
  }, [userId, users]);

  const loadUserDetail = async (id: string) => {
    setLoading(true);
    try {
      // ✅ 从 users 列表中查找并深度复制，避免引用问题
      const foundUser = users.find(u => u.id === id);
      if (foundUser) {
        // ✅ 使用 JSON 序列化来彻底清除任何可能的对象引用问题
        const cleanUser = JSON.parse(JSON.stringify(foundUser));
        console.log('🔍 UserDetailDrawer: Loading user', {
          userId: id,
          cleanUserKeys: Object.keys(cleanUser),
          cleanUser,
        });
        setUser(cleanUser);
      } else {
        console.warn('⚠️ UserDetailDrawer: User not found', { userId: id, totalUsers: users.length });
        setUser(null);
      }
    } catch (error) {
      console.error('Failed to load user detail:', error);
      toast.error('加载用户详情失败');
    } finally {
      setLoading(false);
    }
  };

  const handlePrevious = () => {
    if (hasPrevious && users[currentIndex - 1]) {
      loadUserDetail(users[currentIndex - 1].id);
    }
  };

  const handleNext = () => {
    if (hasNext && users[currentIndex + 1]) {
      loadUserDetail(users[currentIndex + 1].id);
    }
  };

  const handleEdit = () => {
    if (user && onEdit) {
      onEdit(user.id);
    }
  };

  if (!userId) return null;

  return (
    <>
      {/* Backdrop - 独立模式显示深色遮罩，嵌套模式显示浅色遮罩覆盖外层 */}
      <div 
        className="fixed inset-0 z-[60]"
        style={{ backgroundColor: nested ? 'rgba(255, 255, 255, 0.5)' : 'rgba(0, 0, 0, 0.3)' }}
        onClick={onClose}
      />
      
      {/* Drawer */}
      <div
        className="fixed right-0 top-0 bottom-0 z-[70] bg-white shadow-lg flex flex-col"
        style={{ width: '480px' }}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Close Button - Fixed Position */}
        <button
          onClick={onClose}
          className="absolute top-5 right-5 z-10 p-2 rounded-full hover:bg-gray-100 transition-colors"
          style={{ backgroundColor: 'rgba(255, 255, 255, 0.9)' }}
        >
          <X className="w-5 h-5" style={{ color: 'rgb(31, 35, 41)' }} />
        </button>

        {/* Content */}
        <div className="flex-1 overflow-y-auto" style={{ padding: '20px 20px 20px 20px' }}>
          {/* Navigation Buttons - Only show when there are multiple users */}
          {users.length > 1 && (
            <div className="flex items-center justify-end gap-2 mb-6 pr-12">
                <button
                  disabled={!hasPrevious}
                  onClick={handlePrevious}
                  className={`flex items-center gap-1 px-3 py-1.5 text-sm rounded transition-colors ${
                    !hasPrevious 
                      ? 'text-gray-300 cursor-not-allowed' 
                      : 'text-gray-700 hover:bg-gray-100'
                  }`}
                >
                  <ChevronLeft className="w-4 h-4" />
                  {'上一个'}
                </button>
                <button
                  disabled={!hasNext}
                  onClick={handleNext}
                  className={`flex items-center gap-1 px-3 py-1.5 text-sm rounded transition-colors ${
                    !hasNext 
                      ? 'text-gray-300 cursor-not-allowed' 
                      : 'text-gray-700 hover:bg-gray-100'
                  }`}
                >
                  {'下一个'}
                  <ChevronRight className="w-4 h-4" />
                </button>
            </div>
          )}

          {loading ? (
            <div className="flex items-center justify-center h-64">
              <div className="text-gray-500">{'加载中...'}</div>
            </div>
          ) : user ? (
            <>
              {/* Avatar & Basic Info */}
              <div className="mb-6">
                <div className="flex items-start gap-4">
                  <UserAvatar 
                    avatar={user.avatar}
                    displayName={user.displayName}
                    size="lg"
                  />
                  
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-2">
                      <h3 className="text-xl font-semibold truncate" style={{ color: 'rgb(31, 35, 41)' }}>
                        {user.displayName}
                      </h3>
                      <span 
                        className={`px-2 py-0.5 text-xs rounded ${
                          user.status === 'ACTIVE' 
                            ? 'bg-green-100 text-green-700' 
                            : 'bg-gray-100 text-gray-600'
                        }`}
                      >
                        {user.status === 'ACTIVE' 
                          ? ('在职')
                          : user.status
                        }
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              {/* Tabs */}
              <div className="border-b border-dashed mb-6" style={{ borderColor: 'rgb(229, 230, 235)' }}>
                <div className="flex gap-7">
                  <button
                    onClick={() => setActiveTab('basic')}
                    className={`pb-3 text-sm font-medium transition-colors relative ${
                      activeTab === 'basic'
                        ? 'text-blue-600'
                        : 'text-gray-600 hover:text-gray-900'
                    }`}
                  >
                    {'基本信息'}
                    {activeTab === 'basic' && (
                      <div 
                        className="absolute bottom-0 left-0 right-0 h-0.5 bg-blue-600"
                        style={{ borderRadius: '2px 2px 0 0' }}
                      />
                    )}
                  </button>
                  <button
                    onClick={() => setActiveTab('job')}
                    className={`pb-3 text-sm font-medium transition-colors relative ${
                      activeTab === 'job'
                        ? 'text-blue-600'
                        : 'text-gray-600 hover:text-gray-900'
                    }`}
                  >
                    {'工作信息'}
                    {activeTab === 'job' && (
                      <div 
                        className="absolute bottom-0 left-0 right-0 h-0.5 bg-blue-600"
                        style={{ borderRadius: '2px 2px 0 0' }}
                      />
                    )}
                  </button>
                </div>
              </div>

              {/* Tab Content */}
              <div>
                {activeTab === 'basic' && <BasicInfoTab user={user} t={t} />}
                {activeTab === 'job' && <JobDetailsTab user={user} t={t} />}
              </div>
            </>
          ) : (
            <div className="flex items-center justify-center h-64">
              <div className="text-gray-500">{'用户不存在'}</div>
            </div>
          )}
        </div>

        {/* Footer */}
        {user && onEdit && (
          <div className="border-t border-dashed" style={{ padding: '20px', borderColor: 'rgb(229, 230, 235)' }}>
            <div className="flex justify-end">
              <button
                onClick={handleEdit}
                className="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 transition-colors"
              >
                {'编辑基本信息'}
              </button>
            </div>
          </div>
        )}
      </div>
    </>
  );
}

// 基本信息 Tab
function BasicInfoTab({ user, t }: { user: User; t: any }) {
  const formatValue = (value: any) => {
    if (value === null || value === undefined || value === '') {
      return '--';
    }
    // 如果是对象，尝试提取有意义的值
    if (typeof value === 'object') {
      return '--';
    }
    return String(value);
  };

  return (
    <div>
      <FormField label={'姓名'} value={formatValue(user.displayName)} />
      <FormField label={'用户名'} value={formatValue(user.username)} />
      <FormField label={'用户 ID'} value={user.id ? user.id.substring(0, 8) : '--'} />
      <FormField label={'手机号'} value={formatValue(user.phone)} />
      <FormField label={'邮箱'} value={formatValue(user.email)} />
      <FormField 
        label={'部门'} 
        value={user.department?.name || '--'}
      />
      <FormField 
        label={'员工编号'} 
        value={formatValue(user.employeeId)} 
      />
      <FormField 
        label={'状态'} 
        value={formatValue(user.status)}
      />
    </div>
  );
}

// 工作信息 Tab
function JobDetailsTab({ user, t }: { user: User; t: any }) {
  const formatValue = (value: any) => {
    if (value === null || value === undefined || value === '') {
      return '--';
    }
    // 如果是对象，尝试提取有意义的值
    if (typeof value === 'object') {
      return '--';
    }
    return String(value);
  };

  const formatDate = (dateStr: string | null | undefined) => {
    if (!dateStr) return '--';
    try {
      return new Date(dateStr).toLocaleDateString();
    } catch {
      return '--';
    }
  };

  return (
    <div>
      <FormField 
        label={'入职日期'} 
        value={formatDate(user.hiredAt)} 
      />
      <FormField 
        label={'国家/地区'} 
        value={formatValue(user.region)} 
      />
      <FormField 
        label={'直属上级'} 
        value={user.manager?.displayName || '--'} 
      />
      <FormField 
        label={'职位'} 
        value={user.position?.name || '--'} 
      />
      <FormField 
        label={'来源'} 
        value={formatValue(user.source) || 'LOCAL'} 
      />
      
      {/* 多部门归属 - 暂时禁用以排查问题 */}
      {false && user.departmentMemberships && user.departmentMemberships.length > 0 && (
        <div className="mt-8">
          <div className="text-xs font-medium mb-3" style={{ color: 'rgb(140, 146, 164)' }}>
            多部门归属（已禁用）
          </div>
        </div>
      )}
    </div>
  );
}

// 自定义信息 Tab
function CustomInfoTab({ user, t }: { user: User; t: any }) {
  return (
    <div className="space-y-4">
      <div className="text-center py-8 text-gray-500">
        {String((t.organization?.userDetail as any)?.noCustomInfo || 'No custom information available')}
      </div>
    </div>
  );
}

// 表单字段组件
function FormField({ label, value }: { label: any; value: any }) {
  // 确保 label 是可以渲染的原始类型
  const displayLabel = (() => {
    if (label === null || label === undefined) return '';
    if (typeof label === 'object') return JSON.stringify(label);
    return String(label);
  })();
  
  // 确保 value 是可以渲染的原始类型
  const displayValue = (() => {
    if (value === null || value === undefined || value === '') return '--';
    if (typeof value === 'object') return JSON.stringify(value);
    return String(value);
  })();
  
  return (
    <div className="mb-6">
      <div className="text-xs font-medium mb-2" style={{ color: 'rgb(140, 146, 164)' }}>
        {displayLabel}
      </div>
      <div className="text-sm" style={{ color: 'rgb(31, 35, 41)' }}>
        {displayValue}
      </div>
    </div>
  );
}
