import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { motion } from 'framer-motion';
import { useResponsive } from '../hooks/useResponsive';
import type { UserRole } from '../types';

const roles: { id: UserRole; name: string; icon: string; desc: string; gradient: string; shadowColor: string }[] = [
  { id: 'purchaser', name: '采购商（布行）', icon: 'fa-store', desc: '管理采购计划、工厂协作', gradient: 'from-blue-500 to-cyan-500', shadowColor: 'shadow-blue-500/30' },
  { id: 'textile', name: '纺织厂', icon: 'fa-industry', desc: '生产管理、原料追踪', gradient: 'from-emerald-500 to-green-500', shadowColor: 'shadow-emerald-500/30' },
  { id: 'washing', name: '水洗厂', icon: 'fa-water', desc: '水洗加工、成品处理', gradient: 'from-purple-500 to-violet-500', shadowColor: 'shadow-purple-500/30' }
];

export function RoleSelectPage() {
  const navigate = useNavigate();
  const { auth, selectRole } = useAuth();
  const { isMobile } = useResponsive();
  const [hasRedirected, setHasRedirected] = useState(false);

  useEffect(() => {
    // 添加延迟确保数据完全加载，避免竞态条件
    if (auth.isLoggedIn && auth.company && auth.currentRole && !hasRedirected) {
      setHasRedirected(true);
      // 使用 setTimeout 确保状态更新完成后再跳转
      setTimeout(() => {
        navigate(`/${auth.currentRole}`);
      }, 100);
    }
  }, [auth.isLoggedIn, auth.company, auth.currentRole, navigate, hasRedirected]);

  // 显示加载状态，避免在数据加载过程中显示角色选择
  if (auth.isLoggedIn && auth.company && auth.currentRole) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-blue-900 to-indigo-900 flex items-center justify-center">
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="text-center"
        >
          <div className="w-12 h-12 border-4 border-blue-400/30 border-t-blue-400 rounded-full animate-spin mx-auto mb-4" />
          <p className="text-blue-200">正在进入系统...</p>
        </motion.div>
      </div>
    );
  }

  const handleSelect = (role: UserRole) => {
    selectRole(role);
    navigate(`/${role}`);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 via-blue-900 to-indigo-900 flex items-center justify-center p-4 md:p-8 relative overflow-hidden">
      {/* 背景装饰 */}
      <div className="absolute inset-0 overflow-hidden">
        <div className="absolute -top-40 -right-40 w-80 h-80 bg-gradient-to-br from-blue-400/20 to-purple-400/20 rounded-full blur-3xl animate-pulse" />
        <div className="absolute -bottom-40 -left-40 w-80 h-80 bg-gradient-to-br from-green-400/20 to-blue-400/20 rounded-full blur-3xl animate-pulse" style={{ animationDelay: '1s' }} />
      </div>

      <div className="w-full max-w-md md:max-w-6xl relative z-10">
        <motion.div
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
          className="text-center mb-8 md:mb-16"
        >
          <h1 className="text-3xl md:text-5xl font-bold text-white mb-3 md:mb-4">选择您的身份</h1>
          <p className="text-blue-200/70 text-base md:text-xl">请选择您要进入的系统角色</p>
          {auth.user && (
            <motion.p
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.3 }}
              className="text-sm text-blue-300 mt-3"
            >
              当前用户: {auth.user.username}
            </motion.p>
          )}
        </motion.div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 md:gap-10">
          {roles.map((role, i) => (
            <motion.button
              key={role.id}
              initial={{ opacity: 0, y: 30, scale: 0.95 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              transition={{ delay: 0.2 + i * 0.15, duration: 0.5, ease: 'easeOut' }}
              whileHover={{ scale: isMobile ? 1 : 1.05, y: isMobile ? 0 : -8 }}
              whileTap={{ scale: 0.95 }}
              onClick={() => handleSelect(role.id)}
              className="group bg-white/10 backdrop-blur-xl rounded-2xl md:rounded-3xl p-6 md:p-12 border border-white/20 shadow-lg hover:shadow-2xl transition-all duration-300 text-left"
            >
              <motion.div
                initial={{ scale: 0.8 }}
                animate={{ scale: 1 }}
                transition={{ delay: 0.3 + i * 0.15, type: 'spring' }}
                className={`w-16 h-16 md:w-24 md:h-24 rounded-xl md:rounded-2xl flex items-center justify-center mb-6 md:mb-10 bg-gradient-to-br ${role.gradient} ${role.shadowColor} shadow-lg`}
              >
                <i className={`fas ${role.icon} text-3xl md:text-5xl text-white`} />
              </motion.div>
              <h3 className="text-xl md:text-3xl font-bold text-white mb-2 md:mb-4">{role.name}</h3>
              <p className="text-blue-200/60 text-sm md:text-lg mb-4 md:mb-8">{role.desc}</p>
              <div className="flex items-center text-sm md:text-lg font-medium">
                <span className="text-white/80">进入系统</span>
                <i className="fas fa-arrow-right ml-2 md:ml-3 text-white/60 transition-transform group-hover:translate-x-1 group-hover:text-white" />
              </div>
            </motion.button>
          ))}
        </div>
      </div>
    </div>
  );
}