import React, { useState, useEffect, useRef } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useAppDispatch } from '../store/hooks';
import { registerUser } from '../store/slices/authThunks';
import toast from 'react-hot-toast';
import { validatePhoneNumber, validateEmail, validatePassword, validateName } from '../utils/validation';
import { 
  Eye, 
  EyeOff, 
  Mail, 
  Lock, 
  User, 
  Building, 
  Phone,
  Sun, 
  Moon,
  ArrowRight,
  ArrowLeft,
  AlertCircle,
  Cloud,
  Zap,
  MapPin,
  Globe,
  FileText,
  Briefcase,
  Users,
  TrendingUp,
  Calendar,
  Hash,
  CheckCircle,
  Circle
} from 'lucide-react';
import { useAppSelector } from '../store/hooks';
import { RootState } from '../store';
import { toggleTheme } from '../store/slices/themeSlice';
import { cn } from '../utils/cn';

interface FormData {
    firstName: string;
    lastName: string;
    email: string;
    password: string;
    confirmPassword: string;
    phone: string;
    company: string;
    companyType: 'corporation' | 'llc' | 'partnership' | 'sole_proprietorship' | 'other' | '';
    registrationNumber: string;
    gstNumber: string;
    panNumber: string;
    address: string;
    website: string;
    businessLicense: string;
    taxId: string;
    industry: string;
    yearsInBusiness: string;
    annualRevenue: string;
    employeeCount: string;
}

const Signup: React.FC = () => {
  const [currentStep, setCurrentStep] = useState(1);
  const [formData, setFormData] = useState<FormData>({
    firstName: '',
    lastName: '',
    email: '',
    password: '',
    confirmPassword: '',
    phone: '',
    company: '',
    companyType: '',
    registrationNumber: '',
    gstNumber: '',
    panNumber: '',
    address: '',
    website: '',
    businessLicense: '',
    taxId: '',
    industry: '',
    yearsInBusiness: '',
    annualRevenue: '',
    employeeCount: ''
  });
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [agreedToTerms, setAgreedToTerms] = useState(false);
  const [showCompanyTypeDropdown, setShowCompanyTypeDropdown] = useState(false);
  const [showIndustryDropdown, setShowIndustryDropdown] = useState(false);
  
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const { theme } = useAppSelector((state: RootState) => state.theme);

  const totalSteps = 4;

  const companyTypes = [
    { value: 'corporation', label: 'Corporation' },
    { value: 'llc', label: 'LLC' },
    { value: 'partnership', label: 'Partnership' },
    { value: 'sole_proprietorship', label: 'Sole Proprietorship' },
    { value: 'other', label: 'Other' }
  ];

  const industries = [
    'Technology Services', 'IT Consulting', 'Cloud Services', 
    'Software Development', 'Digital Marketing', 'E-commerce',
    'Healthcare IT', 'Financial Services', 'Education Technology',
    'Manufacturing', 'Retail', 'Telecommunications',
    'Energy', 'Transportation', 'Real Estate',
    'Media & Entertainment', 'Professional Services', 'Other'
  ];

  // Close dropdowns when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Element;
      if (!target.closest('.dropdown-container')) {
        setShowCompanyTypeDropdown(false);
        setShowIndustryDropdown(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    setError(''); // Clear error when user starts typing
  };

  const validateStep = (step: number): boolean => {
    setError('');

    switch (step) {
      case 1:
    if (!validateName(formData.firstName)) {
      setError('First name must be between 2 and 50 characters');
          return false;
    }
    if (!validateName(formData.lastName)) {
      setError('Last name must be between 2 and 50 characters');
          return false;
    }
    if (!validateEmail(formData.email)) {
      setError('Please enter a valid email address');
          return false;
    }
        if (!validatePhoneNumber(formData.phone)) {
          setError('Please enter a valid phone number');
          return false;
        }
        break;

      case 2:
    if (!validatePassword(formData.password)) {
      setError('Password must be at least 8 characters with uppercase, lowercase, number, and special character');
          return false;
    }
    if (formData.password !== formData.confirmPassword) {
      setError('Passwords do not match');
          return false;
    }
    if (!formData.company || formData.company.trim().length === 0) {
          setError('Company name is required');
          return false;
    }
        break;

      case 3:
    if (!formData.companyType) {
          setError('Company type is required');
          return false;
    }
    if (!formData.registrationNumber || formData.registrationNumber.trim().length === 0) {
          setError('Registration number is required');
          return false;
    }
    if (!formData.address || formData.address.trim().length === 0) {
      setError('Business address is mandatory for vendor registration');
          return false;
    }

        if (formData.address.trim().length < 10) {
          setError(`Business address must be at least 10 characters long. Current length: ${formData.address.trim().length} characters`);
          return false;
        }
        break;

      case 4:
    if (!formData.industry || formData.industry.trim().length === 0) {
          setError('Industry is required');
          return false;
    }
    if (!formData.yearsInBusiness || formData.yearsInBusiness.trim().length === 0) {
          setError('Years in business is required');
          return false;
    }
    if (!formData.employeeCount || formData.employeeCount.trim().length === 0) {
          setError('Number of employees is required');
          return false;
    }
    if (isNaN(Number(formData.yearsInBusiness)) || Number(formData.yearsInBusiness) < 0) {
      setError('Years in business must be a valid number');
          return false;
    }
    if (isNaN(Number(formData.employeeCount)) || Number(formData.employeeCount) < 1) {
      setError('Number of employees must be at least 1');
          return false;
    }
    if (formData.annualRevenue && (isNaN(Number(formData.annualRevenue)) || Number(formData.annualRevenue) < 0)) {
      setError('Annual revenue must be a valid number');
          return false;
    }
    if (!agreedToTerms) {
      setError('Please agree to the terms and conditions');
          return false;
        }
        break;
    }

    return true;
  };

  const nextStep = () => {
    if (validateStep(currentStep)) {
      setCurrentStep(prev => Math.min(prev + 1, totalSteps));
    }
  };

  const prevStep = () => {
    setCurrentStep(prev => Math.max(prev - 1, 1));
    setError('');
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateStep(currentStep)) {
      return;
    }

    setIsLoading(true);

    try {
      // Prepare the registration data, only including fields with actual values
      const registrationData: any = {
        firstName: formData.firstName,
        lastName: formData.lastName,
        email: formData.email,
        password: formData.password,
        phone: formData.phone,
        company: formData.company,
        // Vendor-specific fields
        companyType: formData.companyType || undefined,
        registrationNumber: formData.registrationNumber,
        address: formData.address,
        industry: formData.industry,
        yearsInBusiness: formData.yearsInBusiness,
        employeeCount: formData.employeeCount,
        role: 'channel_partner_admin',
        userType: 'channel_partner'
      };

      // Only add optional fields if they have values
      if (formData.gstNumber && formData.gstNumber.trim()) {
        registrationData.gstNumber = formData.gstNumber;
      }
      if (formData.panNumber && formData.panNumber.trim()) {
        registrationData.panNumber = formData.panNumber;
      }
      if (formData.website && formData.website.trim()) {
        registrationData.website = formData.website;
      }
      if (formData.businessLicense && formData.businessLicense.trim()) {
        registrationData.businessLicense = formData.businessLicense;
      }
      if (formData.taxId && formData.taxId.trim()) {
        registrationData.taxId = formData.taxId;
      }
      if (formData.annualRevenue && formData.annualRevenue.trim()) {
        registrationData.annualRevenue = formData.annualRevenue;
      }

      await dispatch(registerUser(registrationData)).unwrap();

      navigate('/login', { 
        state: { 
          message: 'Registration successful! You can now login.' 
        } 
      });
    } catch (err: any) {
      const errorMessage = err.message || 'An error occurred during signup. Please try again.';
      setError(errorMessage);
      toast.error(errorMessage);
    } finally {
      setIsLoading(false);
    }
  };

  const handleThemeToggle = () => {
    dispatch(toggleTheme());
  };

  const renderStepIndicator = () => {
  return (
      <div className="flex items-center justify-center mb-8">
        {Array.from({ length: totalSteps }, (_, index) => (
          <div key={index} className="flex items-center">
            <div className={cn(
              "flex items-center justify-center w-8 h-8 rounded-full border-2 transition-all duration-200",
              currentStep > index + 1 
                ? "bg-green-500 border-green-500 text-white" 
                : currentStep === index + 1
                ? "bg-blue-500 border-blue-500 text-white"
                : "bg-white dark:bg-slate-700 border-slate-300 dark:border-slate-600 text-slate-500"
            )}>
              {currentStep > index + 1 ? (
                <CheckCircle className="w-5 h-5" />
              ) : (
                <span className="text-sm font-medium">{index + 1}</span>
              )}
              </div>
            {index < totalSteps - 1 && (
              <div className={cn(
                "w-12 h-0.5 mx-2 transition-all duration-200",
                currentStep > index + 1 ? "bg-green-500" : "bg-slate-300 dark:bg-slate-600"
              )} />
            )}
            </div>
        ))}
          </div>
    );
  };

  const renderStepContent = () => {
    switch (currentStep) {
      case 1:
        return (
          <div className="space-y-6">
            <div>
              <h2 className="text-xl font-semibold text-slate-900 dark:text-white mb-2">
                Personal Information
              </h2>
          <p className="text-slate-600 dark:text-slate-400">
                Let's start with your basic information
          </p>
        </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label htmlFor="firstName" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  First Name
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <User className="h-5 w-5 text-slate-400" />
                  </div>
                  <input
                    id="firstName"
                    type="text"
                    value={formData.firstName}
                    onChange={(e) => handleInputChange('firstName', e.target.value)}
                    className="block w-full pl-10 pr-3 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="Enter first name"
                    required
                  />
                </div>
              </div>

              <div>
                <label htmlFor="lastName" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  Last Name
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <User className="h-5 w-5 text-slate-400" />
                  </div>
                  <input
                    id="lastName"
                    type="text"
                    value={formData.lastName}
                    onChange={(e) => handleInputChange('lastName', e.target.value)}
                    className="block w-full pl-10 pr-3 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="Enter last name"
                    required
                  />
                </div>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label htmlFor="email" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  Email Address
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Mail className="h-5 w-5 text-slate-400" />
                  </div>
                  <input
                    id="email"
                    type="email"
                    value={formData.email}
                    onChange={(e) => handleInputChange('email', e.target.value)}
                    className="block w-full pl-10 pr-3 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="Enter email address"
                    required
                  />
                </div>
              </div>

              <div>
                <label htmlFor="phone" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  Phone Number
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Phone className="h-5 w-5 text-slate-400" />
                  </div>
                  <input
                    id="phone"
                    type="tel"
                    value={formData.phone}
                    onChange={(e) => handleInputChange('phone', e.target.value)}
                    className="block w-full pl-10 pr-3 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="Enter phone number"
                    required
                  />
                </div>
              </div>
            </div>
          </div>
        );

      case 2:
        return (
          <div className="space-y-6">
            <div>
              <h2 className="text-xl font-semibold text-slate-900 dark:text-white mb-2">
                Account Security
              </h2>
              <p className="text-slate-600 dark:text-slate-400">
                Create a secure password and provide company information
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label htmlFor="password" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  Password
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Lock className="h-5 w-5 text-slate-400" />
                  </div>
                  <input
                    id="password"
                    type={showPassword ? 'text' : 'password'}
                    value={formData.password}
                    onChange={(e) => handleInputChange('password', e.target.value)}
                    className="block w-full pl-10 pr-12 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="Create password"
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute inset-y-0 right-0 pr-3 flex items-center"
                  >
                    {showPassword ? (
                      <EyeOff className="h-5 w-5 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300" />
                    ) : (
                      <Eye className="h-5 w-5 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300" />
                    )}
                  </button>
                </div>
              </div>

              <div>
                <label htmlFor="confirmPassword" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  Confirm Password
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Lock className="h-5 w-5 text-slate-400" />
                  </div>
                  <input
                    id="confirmPassword"
                    type={showConfirmPassword ? 'text' : 'password'}
                    value={formData.confirmPassword}
                    onChange={(e) => handleInputChange('confirmPassword', e.target.value)}
                    className="block w-full pl-10 pr-12 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="Confirm password"
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                    className="absolute inset-y-0 right-0 pr-3 flex items-center"
                  >
                    {showConfirmPassword ? (
                      <EyeOff className="h-5 w-5 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300" />
                    ) : (
                      <Eye className="h-5 w-5 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300" />
                    )}
                  </button>
                </div>
              </div>
            </div>

            <div>
              <label htmlFor="company" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                Company Name
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <Building className="h-5 w-5 text-slate-400" />
                </div>
                <input
                  id="company"
                  type="text"
                  value={formData.company}
                  onChange={(e) => handleInputChange('company', e.target.value)}
                  className="block w-full pl-10 pr-3 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                  placeholder="Enter company name"
                  required
                />
              </div>
            </div>
          </div>
        );

      case 3:
        return (
          <div className="space-y-6">
            <div>
              <h2 className="text-xl font-semibold text-slate-900 dark:text-white mb-2">
                Business Details
              </h2>
              <p className="text-slate-600 dark:text-slate-400">
                Provide your business registration and contact information
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                             <div>
                 <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                   Company Type
                 </label>
                 <div className="relative dropdown-container">
                   <button
                     type="button"
                     onClick={() => setShowCompanyTypeDropdown(!showCompanyTypeDropdown)}
                     className="w-full flex items-center justify-between px-3 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                   >
                     <div className="flex items-center">
                       <Briefcase className="h-5 w-5 text-slate-400 mr-3" />
                       <span className={formData.companyType ? 'text-slate-900 dark:text-white' : 'text-slate-500 dark:text-slate-400'}>
                         {formData.companyType ? companyTypes.find(t => t.value === formData.companyType)?.label : 'Select company type'}
                       </span>
                     </div>
                     <svg className="h-5 w-5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                       <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                     </svg>
                   </button>
                   
                   {showCompanyTypeDropdown && (
                     <div className="absolute z-10 w-full mt-1 bg-white dark:bg-slate-700 border border-slate-300 dark:border-slate-600 rounded-xl shadow-lg max-h-48 overflow-y-auto">
                       {companyTypes.map((type) => (
                         <button
                           key={type.value}
                           type="button"
                           onClick={() => {
                             handleInputChange('companyType', type.value);
                             setShowCompanyTypeDropdown(false);
                           }}
                           className="w-full text-left px-3 py-2 hover:bg-slate-50 dark:hover:bg-slate-600 transition-colors duration-200 first:rounded-t-xl last:rounded-b-xl"
                         >
                           {type.label}
                         </button>
                       ))}
                     </div>
                   )}
                 </div>
               </div>

              <div>
                <label htmlFor="registrationNumber" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  Registration Number
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <FileText className="h-5 w-5 text-slate-400" />
                  </div>
                  <input
                    id="registrationNumber"
                    type="text"
                    value={formData.registrationNumber}
                    onChange={(e) => handleInputChange('registrationNumber', e.target.value)}
                    className="block w-full pl-10 pr-3 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="e.g., 1234567890"
                    required
                  />
                </div>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label htmlFor="gstNumber" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  GST Number (Optional)
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Hash className="h-5 w-5 text-slate-400" />
                  </div>
                  <input
                    id="gstNumber"
                    type="text"
                    value={formData.gstNumber}
                    onChange={(e) => handleInputChange('gstNumber', e.target.value)}
                    className="block w-full pl-10 pr-3 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="e.g., 24ABCDE1234F1Z9"
                  />
                </div>
              </div>

              <div>
                <label htmlFor="panNumber" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  PAN Number (Optional)
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Hash className="h-5 w-5 text-slate-400" />
                  </div>
                  <input
                    id="panNumber"
                    type="text"
                    value={formData.panNumber}
                    onChange={(e) => handleInputChange('panNumber', e.target.value)}
                    className="block w-full pl-10 pr-3 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="e.g., ABCDE1234F"
                  />
                </div>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label htmlFor="address" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  Business Address
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <MapPin className="h-5 w-5 text-slate-400" />
                  </div>
                  <input
                    id="address"
                    type="text"
                    value={formData.address}
                    onChange={(e) => handleInputChange('address', e.target.value)}
                    className="block w-full pl-10 pr-3 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="Enter complete business address (min. 10 characters)"
                    required
                  />
                </div>
                <div className="flex justify-between items-center mt-1">
                  <span className="text-xs text-slate-500 dark:text-slate-400">
                    Minimum 10 characters required
                  </span>
                  <span className={cn(
                    "text-xs font-medium",
                    formData.address.length < 10 
                      ? "text-red-500" 
                      : formData.address.length >= 10 
                      ? "text-green-500" 
                      : "text-slate-500 dark:text-slate-400"
                  )}>
                    {formData.address.length}/10
                  </span>
                </div>
              </div>

              <div>
                <label htmlFor="website" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  Website (Optional)
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Globe className="h-5 w-5 text-slate-400" />
                  </div>
                  <input
                    id="website"
                    type="url"
                    value={formData.website}
                    onChange={(e) => handleInputChange('website', e.target.value)}
                    className="block w-full pl-10 pr-3 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="https://example.com"
                  />
                </div>
              </div>
            </div>
                  </div>
        );

      case 4:
        return (
          <div className="space-y-6">
              <div>
              <h2 className="text-xl font-semibold text-slate-900 dark:text-white mb-2">
                Business Profile
              </h2>
              <p className="text-slate-600 dark:text-slate-400">
                Complete your business profile and agree to terms
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                             <div>
                 <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                   Industry
                 </label>
                 <div className="relative dropdown-container">
                   <button
                     type="button"
                     onClick={() => setShowIndustryDropdown(!showIndustryDropdown)}
                     className="w-full flex items-center justify-between px-3 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                   >
                     <div className="flex items-center">
                       <TrendingUp className="h-5 w-5 text-slate-400 mr-3" />
                       <span className={formData.industry ? 'text-slate-900 dark:text-white' : 'text-slate-500 dark:text-slate-400'}>
                         {formData.industry || 'Select industry'}
                       </span>
                     </div>
                     <svg className="h-5 w-5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                       <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                     </svg>
                   </button>
                   
                   {showIndustryDropdown && (
                     <div className="absolute z-10 w-full mt-1 bg-white dark:bg-slate-700 border border-slate-300 dark:border-slate-600 rounded-xl shadow-lg max-h-48 overflow-y-auto">
                       {industries.map((industry) => (
                         <button
                           key={industry}
                           type="button"
                           onClick={() => {
                             handleInputChange('industry', industry);
                             setShowIndustryDropdown(false);
                           }}
                           className="w-full text-left px-3 py-2 hover:bg-slate-50 dark:hover:bg-slate-600 transition-colors duration-200 first:rounded-t-xl last:rounded-b-xl"
                         >
                           {industry}
                         </button>
                       ))}
                     </div>
                   )}
                 </div>
               </div>

              <div>
                <label htmlFor="yearsInBusiness" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  Years in Business
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Calendar className="h-5 w-5 text-slate-400" />
                  </div>
                  <input
                    id="yearsInBusiness"
                    type="number"
                    value={formData.yearsInBusiness}
                    onChange={(e) => handleInputChange('yearsInBusiness', e.target.value)}
                    className="block w-full pl-10 pr-3 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="e.g., 5"
                    required
                  />
                </div>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label htmlFor="annualRevenue" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  Annual Revenue (Optional)
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <TrendingUp className="h-5 w-5 text-slate-400" />
                  </div>
                  <input
                    id="annualRevenue"
                    type="number"
                    value={formData.annualRevenue}
                    onChange={(e) => handleInputChange('annualRevenue', e.target.value)}
                    className="block w-full pl-10 pr-3 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="e.g., 1000000"
                  />
                </div>
              </div>

              <div>
                <label htmlFor="employeeCount" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  Number of Employees
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Users className="h-5 w-5 text-slate-400" />
                  </div>
                  <input
                    id="employeeCount"
                    type="number"
                    value={formData.employeeCount}
                    onChange={(e) => handleInputChange('employeeCount', e.target.value)}
                    className="block w-full pl-10 pr-3 py-3 border border-slate-300 dark:border-slate-600 rounded-xl bg-white dark:bg-slate-700 text-slate-900 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="e.g., 50"
                    required
                  />
                </div>
              </div>
            </div>

            {/* Terms and Conditions */}
            <div className="flex items-start">
              <input
                id="terms"
                type="checkbox"
                checked={agreedToTerms}
                onChange={(e) => setAgreedToTerms(e.target.checked)}
                className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-slate-300 dark:border-slate-600 rounded mt-1"
              />
              <label htmlFor="terms" className="ml-2 text-sm text-slate-700 dark:text-slate-300">
                I agree to the{' '}
                <Link to="/terms" className="text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 font-medium">
                  Terms and Conditions
                </Link>{' '}
                and{' '}
                <Link to="/privacy" className="text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 font-medium">
                  Privacy Policy
                </Link>
              </label>
            </div>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 dark:from-slate-900 dark:via-slate-800 dark:to-slate-900 flex items-center justify-center p-4">
      {/* Theme Toggle */}
      <button
        onClick={handleThemeToggle}
        className="fixed top-6 right-6 p-3 rounded-full bg-white/80 dark:bg-slate-800 backdrop-blur-sm border border-slate-200 dark:border-slate-700 shadow-lg hover:shadow-xl transition-all duration-300 z-50"
        title={theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
      >
        {theme === 'dark' ? (
          <Sun className="w-5 h-5 text-amber-500" />
        ) : (
          <Moon className="w-5 h-5 text-slate-600" />
        )}
      </button>

      <div className="w-full max-w-2xl">
        {/* Logo and Header */}
        <div className="text-center mb-8">
          <div className="relative inline-flex items-center justify-center w-20 h-20 bg-gradient-to-br from-blue-600 via-indigo-600 to-purple-600 rounded-3xl shadow-2xl mb-6 overflow-hidden">
            <div className="absolute inset-0 bg-gradient-to-br from-white/20 to-transparent"></div>
            <div className="relative flex items-center justify-center">
              <div className="relative">
                <Cloud className="w-10 h-10 text-white drop-shadow-lg" />
                <Zap className="w-5 h-5 text-yellow-300 absolute -top-1 -right-1 drop-shadow-lg" />
              </div>
            </div>
          </div>
          <h1 className="text-3xl font-bold text-slate-900 dark:text-white mb-2">
            Join Cloudtopiaa Connect
          </h1>
          <p className="text-slate-600 dark:text-slate-400">
            Partner with us to offer next-gen cloud services.
          </p>
        </div>

        {/* Step Indicator */}
        {renderStepIndicator()}

        {/* Signup Form */}
        <div className="bg-white/80 dark:bg-slate-800 backdrop-blur-sm rounded-2xl shadow-2xl border border-white/20 dark:border-slate-700 p-8">
          <form onSubmit={handleSubmit}>
            {renderStepContent()}

            {/* Error Message */}
            {error && (
              <div className="flex items-center p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg mt-6">
                <AlertCircle className="h-5 w-5 text-red-500 mr-2 flex-shrink-0" />
                <span className="text-sm text-red-700 dark:text-red-400">{error}</span>
              </div>
            )}

            {/* Navigation Buttons */}
            <div className="flex items-center justify-between mt-8">
              <button
                type="button"
                onClick={prevStep}
                disabled={currentStep === 1}
                className={cn(
                  "flex items-center px-4 py-2 border border-slate-300 dark:border-slate-600 rounded-lg font-medium text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all duration-200",
                  currentStep === 1 && "opacity-50 cursor-not-allowed"
                )}
              >
                <ArrowLeft className="mr-2 h-4 w-4" />
                Previous
              </button>

              {currentStep < totalSteps ? (
                <button
                  type="button"
                  onClick={nextStep}
                  className="flex items-center px-6 py-2 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all duration-200"
                >
                  Next
                  <ArrowRight className="ml-2 h-4 w-4" />
                </button>
              ) : (
            <button
              type="submit"
              disabled={isLoading}
              className={cn(
                    "flex items-center px-6 py-2 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-lg font-medium hover:from-blue-700 hover:to-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all duration-200 shadow-lg hover:shadow-xl",
                isLoading && "opacity-75 cursor-not-allowed"
              )}
            >
              {isLoading ? (
                <div className="flex items-center">
                      <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                  Creating account...
                </div>
              ) : (
                <div className="flex items-center">
                  Create Account
                  <ArrowRight className="ml-2 h-4 w-4" />
                </div>
              )}
            </button>
              )}
            </div>
          </form>

          {/* Sign In Link */}
          <div className="mt-6 text-center">
            <p className="text-sm text-slate-600 dark:text-slate-400">
              Already have an account?{' '}
              <Link
                to="/login"
                className="font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 transition-colors duration-200"
              >
                Sign in here
              </Link>
            </p>
          </div>

          {/* Switch to Reseller */}
          <div className="mt-4 text-center">
            <p className="text-sm text-slate-600 dark:text-slate-400">
              Are you a Reseller?{' '}
              <Link
                to="/reseller/signup"
                className="font-medium text-emerald-600 hover:text-emerald-700 dark:text-emerald-400 dark:hover:text-emerald-300 transition-colors duration-200"
              >
                Sign up here
              </Link>
            </p>
          </div>
        </div>

        {/* Footer */}
        <div className="mt-8 text-center">
          <p className="text-xs text-slate-500 dark:text-slate-400">
            © 2025 Cloudtopiaa. All rights reserved.
          </p>
        </div>
      </div>
    </div>
  );
};

export default Signup; 