'use client';

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

interface UserDetailDrawerSimpleProps {
  userId: string | null;
  users?: User[];
  onClose: () => void;
  onEdit?: (userId: string) => void;
  onNavigate?: (userId: string) => void; // ✅ 新增：用于导航的回调
  nested?: boolean;
}

type TabKey = 'basic' | 'job';

// 日期格式化函数
function formatDate(dateStr: string | null | undefined): string {
  if (!dateStr) return '--';
  try {
    return new Date(dateStr).toLocaleDateString();
  } catch {
    return '--';
  }
}

// 安全的字段渲染组件
function SafeField({ label, value, isDate = false }: { label: string; value: any; isDate?: boolean }) {
  const safeValue = (() => {
    if (value === null || value === undefined || value === '') {
      return '--';
    }
    if (isDate && typeof value === 'string') {
      return formatDate(value);
    }
    if (typeof value === 'object') {
      return JSON.stringify(value);
    }
    return String(value);
  })();

  return (
    <div className="mb-4">
      <div className="text-xs font-medium mb-2" style={{ color: 'rgb(140, 146, 164)' }}>
        {label}
      </div>
      <div className="text-sm" style={{ color: 'rgb(31, 35, 41)' }}>
        {safeValue}
      </div>
    </div>
  );
}

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

  // 当前用户在列表中的索引
  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) {
      const foundUser = users.find(u => u.id === userId);
      if (foundUser) {
        const cleanUser = JSON.parse(JSON.stringify(foundUser));
        setUser(cleanUser);
      }
    }
  }, [userId, users]);

  const handlePrevious = () => {
    if (hasPrevious && users[currentIndex - 1]) {
      const prevUserId = users[currentIndex - 1].id;
      if (onNavigate) {
        // ✅ 使用导航回调通知父组件切换用户
        onNavigate(prevUserId);
      } else {
        // 回退到本地状态更新（保持向后兼容）
        const prevUser = users[currentIndex - 1];
        setUser(JSON.parse(JSON.stringify(prevUser)));
      }
    }
  };

  const handleNext = () => {
    if (hasNext && users[currentIndex + 1]) {
      const nextUserId = users[currentIndex + 1].id;
      if (onNavigate) {
        // ✅ 使用导航回调通知父组件切换用户
        onNavigate(nextUserId);
      } else {
        // 回退到本地状态更新（保持向后兼容）
        const nextUser = users[currentIndex + 1];
        setUser(JSON.parse(JSON.stringify(nextUser)));
      }
    }
  };

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

  if (!userId) return null;

  return (
    <>
      <div 
        className="fixed inset-0 z-[60]"
        style={{ backgroundColor: 'rgba(0, 0, 0, 0.3)' }}
        onClick={onClose}
      />
      
      <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()}
      >
        <button
          onClick={onClose}
          className="absolute top-5 right-5 z-10 p-2 rounded-full hover:bg-gray-100 transition-colors"
        >
          <X className="w-5 h-5" />
        </button>

        <div className="flex-1 overflow-y-auto" style={{ padding: '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>
          )}

          {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">
                    <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' 
                          ? ('在职')
                          : String(user.status)
                        }
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              {/* Tabs */}
              <div className="border-b mb-6">
                <div className="flex gap-7">
                  <button
                    onClick={() => setActiveTab('basic')}
                    className={`pb-3 text-sm font-medium ${
                      activeTab === 'basic' ? 'text-blue-600 border-b-2 border-blue-600' : 'text-gray-600'
                    }`}
                  >
                    基本信息
                  </button>
                  <button
                    onClick={() => setActiveTab('job')}
                    className={`pb-3 text-sm font-medium ${
                      activeTab === 'job' ? 'text-blue-600 border-b-2 border-blue-600' : 'text-gray-600'
                    }`}
                  >
                    工作信息
                  </button>
                </div>
              </div>

              {/* Tab Content */}
              <div>
                {activeTab === 'basic' && (
                  <div>
                    <SafeField label={'姓名'} value={user.displayName} />
                    <SafeField label={'用户名'} value={user.username} />
                    <SafeField label={'用户 ID'} value={user.id ? user.id.substring(0, 8) : '--'} />
                    <SafeField label={'手机号'} value={(user as any).phone} />
                    <SafeField label={'邮箱'} value={user.email} />
                    <SafeField label={'部门'} value={(user as any).department?.name} />
                    <SafeField label={'员工编号'} value={(user as any).employeeId} />
                    <SafeField label={'状态'} value={user.status} />
                  </div>
                )}
                
                {activeTab === 'job' && (
                  <div>
                    <SafeField label={'入职日期'} value={(user as any).hiredAt} isDate />
                    <SafeField label={'国家/地区'} value={(user as any).region} />
                    <SafeField label={'直属上级'} value={(user as any).manager?.displayName} />
                    <SafeField label={'职位'} value={(user as any).position?.name} />
                    <SafeField label={'来源'} value={user.source || 'LOCAL'} />
                  </div>
                )}
              </div>
            </>
          ) : (
            <div className="text-center py-8 text-gray-500">
              {'加载中...'}
            </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>
    </>
  );
}

