import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { motion } from 'framer-motion';
import { Eye, EyeOff, UserPlus, Building2, Factory, Droplets, User, Phone, ArrowLeft, ArrowRight, Check } from 'lucide-react';
import { useResponsive } from '../hooks/useResponsive';
import type { UserRole } from '../types';

const roleOptions: { value: UserRole; label: string; color: string; icon: typeof Building2 }[] = [
  { value: 'purchaser', label: '采购商（布行）', color: 'from-blue-500 to-blue-600', icon: Building2 },
  { value: 'textile', label: '纺织厂', color: 'from-emerald-500 to-green-600', icon: Factory },
  { value: 'washing', label: '水洗厂', color: 'from-purple-500 to-purple-600', icon: Droplets }
];

// 纺织主题背景动画组件
function YarnAnimation() {
  const { isMobile } = useResponsive();
  
  const verticalCount = isMobile ? 6 : 12;
  const horizontalCount = isMobile ? 4 : 8;
  const dotCount = isMobile ? 10 : 20;
  const floatCount = isMobile ? 3 : 5;

  return (
    <div className="absolute inset-0 overflow-hidden pointer-events-none">
      {[...Array(verticalCount)].map((_, i) => (
        <motion.div
          key={`v-${i}`}
          className="absolute top-0 w-px bg-gradient-to-b from-transparent via-amber-100/20 to-transparent"
          style={{ 
            left: `${8 + i * (isMobile ? 16 : 8)}%`,
            height: '100%'
          }}
          animate={{
            opacity: [0.1, 0.3, 0.1],
            scaleX: [1, 1.5, 1]
          }}
          transition={{
            duration: 3 + Math.random() * 2,
            repeat: Infinity,
            ease: "easeInOut",
            delay: i * 0.2
          }}
        />
      ))}

      {[...Array(horizontalCount)].map((_, i) => (
        <motion.div
          key={`h-${i}`}
          className="absolute left-0 h-px bg-gradient-to-r from-transparent via-blue-100/15 to-transparent"
          style={{ 
            top: `${10 + i * (isMobile ? 20 : 12)}%`,
            width: '100%'
          }}
          animate={{
            opacity: [0.1, 0.25, 0.1],
            scaleY: [1, 2, 1]
          }}
          transition={{
            duration: 4 + Math.random() * 2,
            repeat: Infinity,
            ease: "easeInOut",
            delay: i * 0.3
          }}
        />
      ))}

      {[...Array(dotCount)].map((_, i) => (
        <motion.div
          key={`dot-${i}`}
          className="absolute w-1 h-1 rounded-full bg-amber-200/40"
          style={{
            left: `${10 + (i % (isMobile ? 4 : 6)) * (isMobile ? 25 : 15)}%`,
            top: `${15 + Math.floor(i / (isMobile ? 4 : 6)) * (isMobile ? 30 : 20)}%`
          }}
          animate={{
            opacity: [0, 0.6, 0],
            scale: [0.5, 1.5, 0.5]
          }}
          transition={{
            duration: 2 + Math.random(),
            repeat: Infinity,
            ease: "easeInOut",
            delay: Math.random() * 3
          }}
        />
      ))}

      {[...Array(floatCount)].map((_, i) => (
        <motion.div
          key={`float-${i}`}
          className="absolute w-24 h-px bg-gradient-to-r from-transparent via-amber-200/30 to-transparent"
          style={{
            top: `${20 + i * (isMobile ? 25 : 15)}%`,
            left: '-100px'
          }}
          animate={{
            x: ['0vw', '120vw'],
            y: [0, Math.sin(i) * 30, 0],
            opacity: [0, 0.5, 0]
          }}
          transition={{
            duration: 8 + i * 2,
            repeat: Infinity,
            ease: "linear",
            delay: i * 1.5
          }}
        />
      ))}

      <motion.div
        className={`absolute top-1/4 right-1/4 opacity-10 ${isMobile ? 'w-20 h-20' : 'w-32 h-32'}`}
        animate={{ rotate: 360 }}
        transition={{ duration: 60, repeat: Infinity, ease: "linear" }}
      >
        <svg viewBox="0 0 100 100" className="w-full h-full">
          <defs>
            <pattern id="weave" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
              <path d="M0,10 L20,10 M10,0 L10,20" stroke="currentColor" strokeWidth="0.5" fill="none" className="text-amber-100"/>
              <circle cx="10" cy="10" r="2" className="text-blue-100" fill="currentColor"/>
            </pattern>
          </defs>
          <rect width="100" height="100" fill="url(#weave)"/>
        </svg>
      </motion.div>

      <svg className={`absolute bottom-0 left-0 w-full opacity-20 ${isMobile ? 'h-20' : 'h-32'}`} viewBox="0 0 1440 120" preserveAspectRatio="none">
        <motion.path
          d="M0,60 Q360,120 720,60 T1440,60 L1440,120 L0,120 Z"
          fill="url(#yarnGradient)"
          animate={{
            d: [
              "M0,60 Q360,120 720,60 T1440,60 L1440,120 L0,120 Z",
              "M0,60 Q360,0 720,60 T1440,60 L1440,120 L0,120 Z",
              "M0,60 Q360,120 720,60 T1440,60 L1440,120 L0,120 Z"
            ]
          }}
          transition={{ duration: 6, repeat: Infinity, ease: "easeInOut" }}
        />
        <defs>
          <linearGradient id="yarnGradient" x1="0%" y1="0%" x2="100%" y2="0%">
            <stop offset="0%" stopColor="#fbbf24" stopOpacity="0.3"/>
            <stop offset="50%" stopColor="#60a5fa" stopOpacity="0.3"/>
            <stop offset="100%" stopColor="#fbbf24" stopOpacity="0.3"/>
          </linearGradient>
        </defs>
      </svg>
    </div>
  );
}

// 纺织行业Logo组件
function TextileLogo() {
  return (
    <motion.div
      whileHover={{ scale: 1.05 }}
      className="inline-flex items-center justify-center w-20 h-20 bg-gradient-to-br from-amber-500 via-orange-500 to-amber-600 rounded-2xl shadow-2xl shadow-amber-500/30 mb-4"
    >
      <svg className="w-10 h-10 text-white" viewBox="0 0 48 48" fill="none">
        <motion.path
          d="M12 8 L12 40 M20 8 L20 40 M28 8 L28 40 M36 8 L36 40"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          initial={{ pathLength: 0 }}
          animate={{ pathLength: 1 }}
          transition={{ duration: 1, ease: "easeOut" }}
        />
        <motion.path
          d="M8 16 L40 16 M8 24 L40 24 M8 32 L40 32"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          initial={{ pathLength: 0 }}
          animate={{ pathLength: 1 }}
          transition={{ duration: 1, delay: 0.3, ease: "easeOut" }}
        />
        <motion.circle cx="16" cy="16" r="2" fill="currentColor"
          initial={{ scale: 0 }}
          animate={{ scale: 1 }}
          transition={{ delay: 0.8 }}
        />
        <motion.circle cx="24" cy="24" r="2" fill="currentColor"
          initial={{ scale: 0 }}
          animate={{ scale: 1 }}
          transition={{ delay: 0.9 }}
        />
        <motion.circle cx="32" cy="32" r="2" fill="currentColor"
          initial={{ scale: 0 }}
          animate={{ scale: 1 }}
          transition={{ delay: 1 }}
        />
        <motion.ellipse 
          cx="36" cy="20" rx="4" ry="2" 
          fill="currentColor"
          initial={{ x: -10, opacity: 0 }}
          animate={{ x: 0, opacity: 1 }}
          transition={{ delay: 1.2, duration: 0.5 }}
        />
      </svg>
    </motion.div>
  );
}

export function RegisterPage() {
  const navigate = useNavigate();
  const { register } = useAuth();
  const { isMobile } = useResponsive();

  const [formData, setFormData] = useState({
    username: '',
    password: '',
    confirmPassword: '',
    displayName: '',
    companyName: '',
    phone: '',
    role: '' as UserRole | ''
  });
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [step, setStep] = useState(1);

  const validateStep1 = () => {
    if (!formData.username.trim()) return '请输入用户名';
    if (formData.username.length < 3) return '用户名至少3个字符';
    if (!formData.password) return '请输入密码';
    if (formData.password.length < 6) return '密码至少6个字符';
    if (formData.password !== formData.confirmPassword) return '两次输入的密码不一致';
    return '';
  };

  const validateStep2 = () => {
    if (!formData.displayName.trim()) return '请输入姓名';
    if (!formData.companyName.trim()) return '请输入公司名称';
    if (!formData.phone.trim()) return '请输入联系电话';
    if (!formData.role) return '请选择角色类型';
    return '';
  };

  const handleNext = () => {
    const errorMsg = validateStep1();
    if (errorMsg) {
      setError(errorMsg);
      return;
    }
    setError('');
    setStep(2);
  };

  const handleBack = () => {
    setStep(1);
    setError('');
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const errorMsg = validateStep2();
    if (errorMsg) {
      setError(errorMsg);
      return;
    }

    setLoading(true);
    setError('');

    const result = await register({
      username: formData.username,
      password: formData.password,
      displayName: formData.displayName,
      companyName: formData.companyName,
      phone: formData.phone,
      role: formData.role as UserRole
    });

    if (result.success) {
      navigate('/login');
    } else {
      setError(result.error || '注册失败，请检查信息或稍后重试');
    }
    setLoading(false);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-amber-900 flex items-center justify-center p-3 sm:p-4 md:p-8 relative overflow-hidden">
      {/* 纺织主题背景动画 */}
      <YarnAnimation />

      {/* 背景装饰 */}
      <div className="absolute inset-0 overflow-hidden">
        <motion.div
          animate={{
            scale: isMobile ? [1, 1.1, 1] : [1, 1.2, 1],
            opacity: [0.1, 0.2, 0.1]
          }}
          transition={{ duration: isMobile ? 6 : 8, repeat: Infinity, ease: "easeInOut" }}
          className="absolute -top-20 -right-20 w-64 h-64 sm:w-80 sm:h-80 md:w-96 md:h-96 bg-gradient-to-br from-amber-400/20 to-orange-400/20 rounded-full blur-3xl"
        />
        <motion.div
          animate={{
            scale: isMobile ? [1.1, 1, 1.1] : [1.2, 1, 1.2],
            opacity: [0.1, 0.2, 0.1]
          }}
          transition={{ duration: isMobile ? 8 : 10, repeat: Infinity, ease: "easeInOut" }}
          className="absolute -bottom-20 -left-20 w-64 h-64 sm:w-80 sm:h-80 md:w-96 md:h-96 bg-gradient-to-br from-blue-400/20 to-amber-400/20 rounded-full blur-3xl"
        />
      </div>

      <motion.div
        initial={{ opacity: 0, y: 20, scale: 0.98 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        transition={{ duration: 0.5, ease: 'easeOut' }}
        className="w-full max-w-sm sm:max-w-md relative z-10 px-2 sm:px-0"
      >
        {/* Logo 区域 */}
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.15, duration: 0.4 }}
          className="text-center mb-6 sm:mb-8"
        >
          <TextileLogo />
          <h1 className="text-2xl sm:text-3xl font-bold text-white mb-1 sm:mb-2">注册账号</h1>
          <p className="text-amber-200/80 text-xs sm:text-sm">创建您的昱森（Demo版）账号</p>
        </motion.div>

        {/* 步骤指示器 */}
        <motion.div 
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.2, duration: 0.4 }}
          className="flex items-center justify-center gap-3 mb-6"
        >
          <div className={`flex items-center gap-2 ${step >= 1 ? 'text-white' : 'text-white/40'}`}>
            <motion.div 
              className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${step >= 1 ? 'bg-gradient-to-r from-amber-500 to-orange-500' : 'bg-white/20'}`}
              whileHover={{ scale: 1.1 }}
            >
              {step > 1 ? <Check size={16} /> : '1'}
            </motion.div>
            <span className="text-xs sm:text-sm hidden sm:inline">账号信息</span>
          </div>
          <div className="w-10 h-0.5 bg-white/20" />
          <div className={`flex items-center gap-2 ${step >= 2 ? 'text-white' : 'text-white/40'}`}>
            <motion.div 
              className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${step >= 2 ? 'bg-gradient-to-r from-amber-500 to-orange-500' : 'bg-white/20'}`}
              whileHover={{ scale: 1.1 }}
            >
              2
            </motion.div>
            <span className="text-xs sm:text-sm hidden sm:inline">公司信息</span>
          </div>
        </motion.div>

        {/* 注册表单 */}
        <motion.div
          initial={{ opacity: 0, y: 15 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.25, duration: 0.4 }}
          className="bg-white/10 backdrop-blur-xl rounded-2xl p-4 sm:p-6 md:p-8 border border-white/20 shadow-2xl"
        >
          {step === 1 ? (
            <form className="space-y-4 sm:space-y-5">
              <div>
                <label className="block text-xs sm:text-sm font-medium text-amber-200/90 mb-1.5 sm:mb-2">用户名</label>
                <div className="relative">
                  <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 sm:w-5 sm:h-5 text-white/40" />
                  <input
                    type="text"
                    value={formData.username}
                    onChange={e => setFormData({ ...formData, username: e.target.value })}
                    className="w-full pl-10 pr-4 py-2.5 sm:py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/40 focus:ring-2 focus:ring-amber-400/50 focus:border-amber-400/50 transition-all text-sm sm:text-base"
                    placeholder="请输入用户名（至少3个字符）"
                    required
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs sm:text-sm font-medium text-amber-200/90 mb-1.5 sm:mb-2">密码</label>
                <div className="relative">
                  <input
                    type={showPassword ? 'text' : 'password'}
                    value={formData.password}
                    onChange={e => setFormData({ ...formData, password: e.target.value })}
                    className="w-full px-4 py-2.5 sm:py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/40 focus:ring-2 focus:ring-amber-400/50 focus:border-amber-400/50 transition-all pr-12 text-sm sm:text-base"
                    placeholder="请输入密码（至少6个字符）"
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-white/50 hover:text-white/80 transition-colors p-1"
                  >
                    {showPassword ? <EyeOff size={isMobile ? 16 : 18} /> : <Eye size={isMobile ? 16 : 18} />}
                  </button>
                </div>
              </div>

              <div>
                <label className="block text-xs sm:text-sm font-medium text-amber-200/90 mb-1.5 sm:mb-2">确认密码</label>
                <div className="relative">
                  <input
                    type={showConfirmPassword ? 'text' : 'password'}
                    value={formData.confirmPassword}
                    onChange={e => setFormData({ ...formData, confirmPassword: e.target.value })}
                    className="w-full px-4 py-2.5 sm:py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/40 focus:ring-2 focus:ring-amber-400/50 focus:border-amber-400/50 transition-all pr-12 text-sm sm:text-base"
                    placeholder="请再次输入密码"
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-white/50 hover:text-white/80 transition-colors p-1"
                  >
                    {showConfirmPassword ? <EyeOff size={isMobile ? 16 : 18} /> : <Eye size={isMobile ? 16 : 18} />}
                  </button>
                </div>
              </div>

              {error && (
                <motion.p
                  initial={{ opacity: 0, x: -10 }}
                  animate={{ opacity: 1, x: 0 }}
                  className="text-red-400 text-xs sm:text-sm text-center bg-red-400/10 py-2 rounded-lg border border-red-400/20"
                >
                  {error}
                </motion.p>
              )}

              <motion.button
                whileHover={isMobile ? {} : { scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
                type="button"
                onClick={handleNext}
                className="w-full py-3 sm:py-3.5 bg-gradient-to-r from-amber-500 via-orange-500 to-amber-600 text-white rounded-xl font-medium hover:from-amber-600 hover:via-orange-600 hover:to-amber-700 transition-all shadow-lg shadow-amber-500/30 flex items-center justify-center gap-2 text-sm sm:text-base"
              >
                下一步
                <ArrowRight size={isMobile ? 16 : 18} />
              </motion.button>
            </form>
          ) : (
            <form onSubmit={handleSubmit} className="space-y-4 sm:space-y-5">
              <div>
                <label className="block text-xs sm:text-sm font-medium text-amber-200/90 mb-1.5 sm:mb-2">姓名</label>
                <div className="relative">
                  <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 sm:w-5 sm:h-5 text-white/40" />
                  <input
                    type="text"
                    value={formData.displayName}
                    onChange={e => setFormData({ ...formData, displayName: e.target.value })}
                    className="w-full pl-10 pr-4 py-2.5 sm:py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/40 focus:ring-2 focus:ring-amber-400/50 focus:border-amber-400/50 transition-all text-sm sm:text-base"
                    placeholder="请输入姓名"
                    required
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs sm:text-sm font-medium text-amber-200/90 mb-1.5 sm:mb-2">公司名称</label>
                <div className="relative">
                  <Building2 className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 sm:w-5 sm:h-5 text-white/40" />
                  <input
                    type="text"
                    value={formData.companyName}
                    onChange={e => setFormData({ ...formData, companyName: e.target.value })}
                    className="w-full pl-10 pr-4 py-2.5 sm:py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/40 focus:ring-2 focus:ring-amber-400/50 focus:border-amber-400/50 transition-all text-sm sm:text-base"
                    placeholder="请输入公司名称"
                    required
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs sm:text-sm font-medium text-amber-200/90 mb-1.5 sm:mb-2">联系电话</label>
                <div className="relative">
                  <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 sm:w-5 sm:h-5 text-white/40" />
                  <input
                    type="tel"
                    value={formData.phone}
                    onChange={e => setFormData({ ...formData, phone: e.target.value })}
                    className="w-full pl-10 pr-4 py-2.5 sm:py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/40 focus:ring-2 focus:ring-amber-400/50 focus:border-amber-400/50 transition-all text-sm sm:text-base"
                    placeholder="请输入联系电话"
                    required
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs sm:text-sm font-medium text-amber-200/90 mb-1.5 sm:mb-2">角色类型</label>
                <div className="grid grid-cols-3 gap-2 sm:gap-3">
                  {roleOptions.map((role, i) => (
                    <motion.button
                      key={role.value}
                      type="button"
                      onClick={() => setFormData({ ...formData, role: role.value })}
                      initial={{ opacity: 0, y: 10 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: 0.3 + i * 0.08 }}
                      whileHover={{ scale: 1.05 }}
                      whileTap={{ scale: 0.95 }}
                      className={`p-2.5 sm:p-3 rounded-xl border transition-all flex flex-col items-center gap-1 ${
                        formData.role === role.value
                          ? 'border-amber-400 bg-amber-500/20 shadow-lg shadow-amber-500/20'
                          : 'border-white/20 bg-white/5 hover:bg-white/10'
                      }`}
                    >
                      <role.icon size={isMobile ? 16 : 18} className={formData.role === role.value ? 'text-amber-300' : 'text-white/60'} />
                      <p className={`text-xs text-center ${formData.role === role.value ? 'text-white font-medium' : 'text-white/70'}`}>{role.label}</p>
                    </motion.button>
                  ))}
                </div>
              </div>

              {error && (
                <motion.p
                  initial={{ opacity: 0, x: -10 }}
                  animate={{ opacity: 1, x: 0 }}
                  className="text-red-400 text-xs sm:text-sm text-center bg-red-400/10 py-2 rounded-lg border border-red-400/20"
                >
                  {error}
                </motion.p>
              )}

              <div className="flex gap-3">
                <motion.button
                  whileHover={isMobile ? {} : { scale: 1.02 }}
                  whileTap={{ scale: 0.98 }}
                  type="button"
                  onClick={handleBack}
                  className="flex-1 py-3 sm:py-3.5 border border-white/30 text-white rounded-xl font-medium hover:bg-white/10 transition-all flex items-center justify-center gap-2 text-sm sm:text-base"
                >
                  <ArrowLeft size={isMobile ? 16 : 18} />
                  上一步
                </motion.button>
                <motion.button
                  whileHover={isMobile ? {} : { scale: 1.02 }}
                  whileTap={{ scale: 0.98 }}
                  type="submit"
                  disabled={loading}
                  className="flex-1 py-3 sm:py-3.5 bg-gradient-to-r from-amber-500 via-orange-500 to-amber-600 text-white rounded-xl font-medium hover:from-amber-600 hover:via-orange-600 hover:to-amber-700 transition-all shadow-lg shadow-amber-500/30 disabled:opacity-50 flex items-center justify-center gap-2 text-sm sm:text-base"
                >
                  <UserPlus size={isMobile ? 16 : 18} />
                  {loading ? '注册中...' : '完成注册'}
                </motion.button>
              </div>
            </form>
          )}
        </motion.div>

        {/* 登录入口 */}
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.5, duration: 0.4 }}
          className="mt-4 sm:mt-6 text-center"
        >
          <p className="text-amber-200/60 text-xs sm:text-sm">
            已有账号？{' '}
            <Link to="/login" className="text-amber-300 hover:text-amber-200 font-medium transition-colors underline underline-offset-2">
              立即登录
            </Link>
          </p>
        </motion.div>
      </motion.div>
    </div>
  );
}
