'use client';

import { useState, useEffect, useRef } from 'react';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import {
  User,
  Mail,
  Phone,
  Camera,
  Lock,
  Shield,
  Key,
  Save,
  Loader2,
  AlertCircle,
  CheckCircle2,
  X,
  Eye,
  EyeOff,
  Smartphone,
  Mail as MailIcon,
  Globe,
  Github,
  Facebook,
  Apple,
} from 'lucide-react';
import { useUserStore } from '@/stores/userStore';
import toast from 'react-hot-toast';

interface UserProfile {
  id: string;
  email: string;
  first_name: string | null;
  last_name: string | null;
  display_name: string | null;
  avatar_url: string | null;
  phone: string | null;
  email_verified: boolean;
  two_factor_enabled: boolean;
  two_factor_method: string;
  signup_method: string;
  created_at: string;
  updated_at: string;
}

interface PasswordForm {
  current_password: string;
  new_password: string;
  confirm_password: string;
}

interface ProfileForm {
  first_name: string;
  last_name: string;
  display_name: string;
  phone: string;
}

export default function ProfilePage() {
  const router = useRouter();
  const { user, isAuthenticated, updateUser, logout } = useUserStore();
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [isChangingPassword, setIsChangingPassword] = useState(false);
  const [isToggling2FA, setIsToggling2FA] = useState(false);
  const [activeTab, setActiveTab] = useState<'profile' | 'security' | '2fa'>('profile');
  
  // Form states
  const [profileForm, setProfileForm] = useState<ProfileForm>({
    first_name: '',
    last_name: '',
    display_name: '',
    phone: '',
  });
  
  const [passwordForm, setPasswordForm] = useState<PasswordForm>({
    current_password: '',
    new_password: '',
    confirm_password: '',
  });
  
  const [showPasswords, setShowPasswords] = useState({
    current: false,
    new: false,
    confirm: false,
  });
  
  const [passwordErrors, setPasswordErrors] = useState<string[]>([]);
  const [passwordStrength, setPasswordStrength] = useState(0);
  
  // 2FA States
  const [twoFACode, setTwoFACode] = useState('');
  const [show2FAInput, setShow2FAInput] = useState(false);
  const [isVerifying2FA, setIsVerifying2FA] = useState(false);
  const [countdown, setCountdown] = useState(0);

  // Check authentication on mount
  useEffect(() => {
    if (!isAuthenticated) {
      router.push('/login?from=/dashboard/profile');
      return;
    }
    fetchProfile();
  }, [isAuthenticated, router]);

  // Countdown timer for 2FA code resend
  useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
      return () => clearTimeout(timer);
    }
  }, [countdown]);

  const fetchProfile = async () => {
    try {
      const response = await fetch('/api/frontend/user/profile', {
        credentials: 'include', // Important: Include cookies for session
      });

      if (!response.ok) {
        if (response.status === 401) {
          // Token expired or invalid
          logout();
          router.push('/login?from=/dashboard/profile');
          return;
        }
        throw new Error('Failed to fetch profile');
      }

      const data = await response.json();
      setProfile(data.user);
      
      // Initialize form with user data
      setProfileForm({
        first_name: data.user.first_name || '',
        last_name: data.user.last_name || '',
        display_name: data.user.display_name || '',
        phone: data.user.phone || '',
      });
    } catch (error) {
      console.error('Error fetching profile:', error);
      toast.error('Failed to load profile');
    } finally {
      setIsLoading(false);
    }
  };

  const handleProfileUpdate = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!isAuthenticated) {
      toast.error('You must be logged in');
      router.push('/login');
      return;
    }

    setIsSaving(true);

    try {
      const response = await fetch('/api/frontend/user/profile', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify(profileForm),
      });

      const data = await response.json();

      if (!response.ok) {
        if (response.status === 401) {
          logout();
          router.push('/login');
          return;
        }
        throw new Error(data.message || 'Failed to update profile');
      }

      setProfile(data.user);
      updateUser(data.user); // Update store with new user data
      toast.success('Profile updated successfully');
    } catch (error) {
      console.error('Error updating profile:', error);
      toast.error(error instanceof Error ? error.message : 'Failed to update profile');
    } finally {
      setIsSaving(false);
    }
  };

  const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!isAuthenticated) {
      toast.error('You must be logged in');
      router.push('/login');
      return;
    }

    // Validate file type and size
    if (!file.type.startsWith('image/')) {
      toast.error('Please upload an image file');
      return;
    }

    if (file.size > 5 * 1024 * 1024) {
      toast.error('File size must be less than 5MB');
      return;
    }

    const formData = new FormData();
    formData.append('avatar', file);

    setIsUploading(true);

    try {
      const response = await fetch('/api/frontend/user/avatar', {
        method: 'POST',
        credentials: 'include',
        body: formData,
      });

      const data = await response.json();

      if (!response.ok) {
        if (response.status === 401) {
          logout();
          router.push('/login');
          return;
        }
        throw new Error(data.message || 'Failed to upload avatar');
      }

      setProfile(prev => prev ? { ...prev, avatar_url: data.avatar_url } : null);
      updateUser({ avatar_url: data.avatar_url }); // Update store
      toast.success('Avatar updated successfully');
    } catch (error) {
      console.error('Error uploading avatar:', error);
      toast.error(error instanceof Error ? error.message : 'Failed to upload avatar');
    } finally {
      setIsUploading(false);
    }
  };

  const validatePassword = (password: string) => {
    const errors: string[] = [];
    let strength = 0;

    if (password.length < 8) {
      errors.push('Password must be at least 8 characters long');
    } else {
      strength += 25;
    }

    if (/[A-Z]/.test(password)) strength += 25;
    if (/[a-z]/.test(password)) strength += 25;
    if (/[0-9]/.test(password)) strength += 15;
    if (/[^A-Za-z0-9]/.test(password)) strength += 10;

    setPasswordStrength(Math.min(strength, 100));
    return errors;
  };

  const handlePasswordChange = (field: keyof PasswordForm, value: string) => {
    setPasswordForm(prev => ({ ...prev, [field]: value }));
    
    if (field === 'new_password') {
      const errors = validatePassword(value);
      setPasswordErrors(errors);
    }
  };

  const handlePasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!isAuthenticated) {
      toast.error('You must be logged in');
      router.push('/login');
      return;
    }

    // Validate passwords
    if (passwordForm.new_password.length < 8) {
      toast.error('Password must be at least 8 characters long');
      return;
    }

    if (passwordForm.new_password !== passwordForm.confirm_password) {
      toast.error('Passwords do not match');
      return;
    }

    setIsChangingPassword(true);

    try {
      const response = await fetch('/api/frontend/user/password', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({
          current_password: passwordForm.current_password,
          new_password: passwordForm.new_password,
          confirm_password: passwordForm.confirm_password,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        if (response.status === 401) {
          logout();
          router.push('/login');
          return;
        }
        throw new Error(data.message || 'Failed to change password');
      }

      toast.success('Password changed successfully');
      
      // Reset form
      setPasswordForm({
        current_password: '',
        new_password: '',
        confirm_password: '',
      });
      setPasswordErrors([]);
      setPasswordStrength(0);
    } catch (error) {
      console.error('Error changing password:', error);
      toast.error(error instanceof Error ? error.message : 'Failed to change password');
    } finally {
      setIsChangingPassword(false);
    }
  };

  const handleToggle2FA = async () => {
    if (!isAuthenticated) {
      toast.error('You must be logged in');
      router.push('/login');
      return;
    }

    if (!profile?.email_verified) {
      toast.error('Please verify your email first');
      return;
    }

    if (!profile?.two_factor_enabled) {
      // Enable 2FA - send code first
      setIsToggling2FA(true);
      
      try {
        const response = await fetch('/api/frontend/user/2fa/send-code', {
          method: 'POST',
          credentials: 'include',
        });

        const data = await response.json();

        if (!response.ok) {
          if (response.status === 401) {
            logout();
            router.push('/login');
            return;
          }
          throw new Error(data.message || 'Failed to send verification code');
        }

        setShow2FAInput(true);
        setCountdown(60); // 60 seconds cooldown
        toast.success('Verification code sent to your email');
      } catch (error) {
        console.error('Error sending 2FA code:', error);
        toast.error(error instanceof Error ? error.message : 'Failed to send verification code');
      } finally {
        setIsToggling2FA(false);
      }
    } else {
      // Disable 2FA
      setIsToggling2FA(true);
      
      try {
        const response = await fetch('/api/frontend/user/2fa/disable', {
          method: 'POST',
          credentials: 'include',
        });

        const data = await response.json();

        if (!response.ok) {
          if (response.status === 401) {
            logout();
            router.push('/login');
            return;
          }
          throw new Error(data.message || 'Failed to disable 2FA');
        }

        setProfile(prev => prev ? { ...prev, two_factor_enabled: false } : null);
        updateUser({ two_factor_enabled: false }); // Update store
        toast.success('Two-factor authentication disabled');
      } catch (error) {
        console.error('Error disabling 2FA:', error);
        toast.error(error instanceof Error ? error.message : 'Failed to disable 2FA');
      } finally {
        setIsToggling2FA(false);
      }
    }
  };

  const verify2FACode = async () => {
    if (!isAuthenticated) {
      toast.error('You must be logged in');
      router.push('/login');
      return;
    }

    if (!twoFACode || twoFACode.length !== 6) {
      toast.error('Please enter a valid 6-digit code');
      return;
    }

    setIsVerifying2FA(true);

    try {
      const response = await fetch('/api/frontend/user/2fa/verify', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({ code: twoFACode }),
      });

      const data = await response.json();

      if (!response.ok) {
        if (response.status === 401) {
          logout();
          router.push('/login');
          return;
        }
        throw new Error(data.message || 'Invalid verification code');
      }

      setProfile(prev => prev ? { ...prev, two_factor_enabled: true } : null);
      updateUser({ two_factor_enabled: true }); // Update store
      setShow2FAInput(false);
      setTwoFACode('');
      toast.success('Two-factor authentication enabled');
    } catch (error) {
      console.error('Error verifying 2FA code:', error);
      toast.error(error instanceof Error ? error.message : 'Failed to verify code');
    } finally {
      setIsVerifying2FA(false);
    }
  };

  const resend2FACode = async () => {
    if (countdown > 0) return;

    try {
      const response = await fetch('/api/frontend/user/2fa/send-code', {
        method: 'POST',
        credentials: 'include',
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || 'Failed to resend code');
      }

      setCountdown(60);
      toast.success('New verification code sent');
    } catch (error) {
      console.error('Error resending code:', error);
      toast.error(error instanceof Error ? error.message : 'Failed to resend code');
    }
  };

  const getSignupMethodIcon = (method: string) => {
    switch (method) {
      case 'google':
        return <Globe className="h-4 w-4" />;
      case 'facebook':
        return <Facebook className="h-4 w-4" />;
      case 'github':
        return <Github className="h-4 w-4" />;
      case 'apple':
        return <Apple className="h-4 w-4" />;
      default:
        return <Mail className="h-4 w-4" />;
    }
  };

  const getPasswordStrengthColor = () => {
    if (passwordStrength < 40) return 'bg-red-500';
    if (passwordStrength < 70) return 'bg-yellow-500';
    return 'bg-green-500';
  };

  const getPasswordStrengthText = () => {
    if (passwordStrength < 40) return 'Weak';
    if (passwordStrength < 70) return 'Medium';
    return 'Strong';
  };

  if (isLoading) {
    return (
      <div className="min-h-[60vh] flex items-center justify-center">
        <div className="text-center">
          <div className="relative">
            <div className="w-16 h-16 border-4 border-gray-200 dark:border-gray-700 border-t-blue-600 rounded-full animate-spin mx-auto mb-4"></div>
            <p className="text-gray-600 dark:text-gray-400">Loading profile...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Profile Settings</h1>
        <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
          Manage your account settings and preferences
        </p>
      </div>

      {/* Profile tabs */}
      <div className="border-b border-gray-200 dark:border-gray-700">
        <nav className="flex space-x-8">
          <button
            onClick={() => setActiveTab('profile')}
            className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors ${
              activeTab === 'profile'
                ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                : 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300'
            }`}
          >
            Profile Information
          </button>
          <button
            onClick={() => setActiveTab('security')}
            className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors ${
              activeTab === 'security'
                ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                : 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300'
            }`}
          >
            Security
          </button>
          <button
            onClick={() => setActiveTab('2fa')}
            className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors ${
              activeTab === '2fa'
                ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                : 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300'
            }`}
          >
            Two-Factor Authentication
          </button>
        </nav>
      </div>

      {/* Profile Tab */}
      {activeTab === 'profile' && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Avatar Card */}
          <div className="lg:col-span-1">
            <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 border border-gray-200 dark:border-gray-700">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">Profile Picture</h2>
              
              <div className="flex flex-col items-center">
                <div className="relative group">
                  <div className="w-32 h-32 rounded-full overflow-hidden bg-gray-100 dark:bg-gray-700 ring-4 ring-white dark:ring-gray-800">
                    {profile?.avatar_url ? (
                      <Image
                        src={profile.avatar_url}
                        alt="Profile"
                        width={128}
                        height={128}
                        className="w-full h-full object-cover"
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center bg-gradient-to-r from-blue-600 to-purple-600">
                        <span className="text-4xl font-bold text-white">
                          {profile?.first_name?.[0] || profile?.email?.[0] || 'U'}
                        </span>
                      </div>
                    )}
                  </div>
                  
                  <button
                    onClick={() => fileInputRef.current?.click()}
                    disabled={isUploading}
                    className="absolute bottom-0 right-0 p-2 bg-blue-600 hover:bg-blue-700 text-white rounded-full shadow-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isUploading ? (
                      <Loader2 className="h-4 w-4 animate-spin" />
                    ) : (
                      <Camera className="h-4 w-4" />
                    )}
                  </button>
                </div>
                
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  onChange={handleAvatarUpload}
                  className="hidden"
                />
                
                <p className="text-sm text-gray-500 dark:text-gray-400 mt-4">
                  Click the camera icon to upload a new photo
                </p>
                <p className="text-xs text-gray-400 dark:text-gray-500 mt-1">
                  Maximum file size: 5MB. Supported: JPG, PNG, GIF
                </p>
              </div>

              {/* Account Info */}
              <div className="mt-6 pt-6 border-t border-gray-200 dark:border-gray-700">
                <h3 className="text-sm font-medium text-gray-900 dark:text-white mb-3">Account Information</h3>
                
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600 dark:text-gray-400">Email</span>
                    <div className="flex items-center space-x-2">
                      <span className="text-sm font-medium text-gray-900 dark:text-white">{profile?.email}</span>
                      {profile?.email_verified ? (
                        <CheckCircle2 className="h-4 w-4 text-green-500" />
                      ) : (
                        <AlertCircle className="h-4 w-4 text-yellow-500" />
                      )}
                    </div>
                  </div>
                  
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600 dark:text-gray-400">Member since</span>
                    <span className="text-sm font-medium text-gray-900 dark:text-white">
                      {profile?.created_at ? new Date(profile.created_at).toLocaleDateString() : 'N/A'}
                    </span>
                  </div>
                  
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600 dark:text-gray-400">Sign up method</span>
                    <div className="flex items-center space-x-1">
                      {getSignupMethodIcon(profile?.signup_method || 'email')}
                      <span className="text-sm font-medium text-gray-900 dark:text-white capitalize">
                        {profile?.signup_method || 'Email'}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Profile Form */}
          <div className="lg:col-span-2">
            <form onSubmit={handleProfileUpdate} className="bg-white dark:bg-gray-800 rounded-2xl p-6 border border-gray-200 dark:border-gray-700">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-6">Personal Information</h2>
              
              <div className="space-y-6">
                {/* Name fields */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label htmlFor="first_name" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      First Name
                    </label>
                    <input
                      type="text"
                      id="first_name"
                      value={profileForm.first_name}
                      onChange={(e) => setProfileForm(prev => ({ ...prev, first_name: e.target.value }))}
                      className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                      placeholder="Enter your first name"
                    />
                  </div>
                  
                  <div>
                    <label htmlFor="last_name" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Last Name
                    </label>
                    <input
                      type="text"
                      id="last_name"
                      value={profileForm.last_name}
                      onChange={(e) => setProfileForm(prev => ({ ...prev, last_name: e.target.value }))}
                      className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                      placeholder="Enter your last name"
                    />
                  </div>
                </div>

                {/* Display Name */}
                <div>
                  <label htmlFor="display_name" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Display Name
                  </label>
                  <input
                    type="text"
                    id="display_name"
                    value={profileForm.display_name}
                    onChange={(e) => setProfileForm(prev => ({ ...prev, display_name: e.target.value }))}
                    className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                    placeholder="How should we display your name?"
                  />
                  <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    This is how your name will be displayed across the platform
                  </p>
                </div>

                {/* Phone */}
                <div>
                  <label htmlFor="phone" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Phone Number
                  </label>
                  <div className="relative">
                    <Phone className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                    <input
                      type="tel"
                      id="phone"
                      value={profileForm.phone}
                      onChange={(e) => setProfileForm(prev => ({ ...prev, phone: e.target.value }))}
                      className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                      placeholder="Enter your phone number"
                    />
                  </div>
                </div>

                {/* Email (read-only) */}
                <div>
                  <label htmlFor="email" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Email Address
                  </label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                    <input
                      type="email"
                      id="email"
                      value={profile?.email || ''}
                      disabled
                      className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700 text-gray-500 dark:text-gray-400 cursor-not-allowed"
                    />
                  </div>
                  <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    Email cannot be changed. Contact support if you need to update it.
                  </p>
                </div>

                {/* Submit button */}
                <div className="flex justify-end">
                  <button
                    type="submit"
                    disabled={isSaving}
                    className="inline-flex items-center px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isSaving ? (
                      <>
                        <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                        Saving...
                      </>
                    ) : (
                      <>
                        <Save className="h-4 w-4 mr-2" />
                        Save Changes
                      </>
                    )}
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Security Tab */}
      {activeTab === 'security' && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Password Change Form */}
          <div className="lg:col-span-2">
            <form onSubmit={handlePasswordSubmit} className="bg-white dark:bg-gray-800 rounded-2xl p-6 border border-gray-200 dark:border-gray-700">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-6">Change Password</h2>
              
              {profile?.signup_method && profile.signup_method !== 'email' && (
                <div className="mb-6 p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
                  <div className="flex items-start space-x-3">
                    <AlertCircle className="h-5 w-5 text-yellow-600 dark:text-yellow-400 shrink-0 mt-0.5" />
                    <div>
                      <p className="text-sm font-medium text-yellow-800 dark:text-yellow-300">
                        You signed up with {profile.signup_method}
                      </p>
                      <p className="text-sm text-yellow-700 dark:text-yellow-400 mt-1">
                        Setting a password will allow you to log in with email and password as well.
                      </p>
                    </div>
                  </div>
                </div>
              )}
              
              <div className="space-y-4">
                {/* Current Password */}
                <div>
                  <label htmlFor="current_password" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Current Password
                  </label>
                  <div className="relative">
                    <Key className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                    <input
                      type={showPasswords.current ? 'text' : 'password'}
                      id="current_password"
                      value={passwordForm.current_password}
                      onChange={(e) => handlePasswordChange('current_password', e.target.value)}
                      className="w-full pl-10 pr-10 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                      placeholder="Enter your current password"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPasswords(prev => ({ ...prev, current: !prev.current }))}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    >
                      {showPasswords.current ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                    </button>
                  </div>
                </div>

                {/* New Password */}
                <div>
                  <label htmlFor="new_password" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    New Password
                  </label>
                  <div className="relative">
                    <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                    <input
                      type={showPasswords.new ? 'text' : 'password'}
                      id="new_password"
                      value={passwordForm.new_password}
                      onChange={(e) => handlePasswordChange('new_password', e.target.value)}
                      className="w-full pl-10 pr-10 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                      placeholder="Enter new password"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPasswords(prev => ({ ...prev, new: !prev.new }))}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    >
                      {showPasswords.new ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                    </button>
                  </div>
                </div>

                {/* Password Strength Meter */}
                {passwordForm.new_password && (
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <div className="flex-1 h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
                        <div 
                          className={`h-full ${getPasswordStrengthColor()} transition-all duration-300`}
                          style={{ width: `${passwordStrength}%` }}
                        />
                      </div>
                      <span className="ml-3 text-xs font-medium text-gray-600 dark:text-gray-400">
                        {getPasswordStrengthText()}
                      </span>
                    </div>
                    
                    {passwordErrors.length > 0 && (
                      <ul className="space-y-1">
                        {passwordErrors.map((error, index) => (
                          <li key={index} className="text-xs text-red-600 dark:text-red-400 flex items-start">
                            <X className="h-3 w-3 mr-1 shrink-0 mt-0.5" />
                            {error}
                          </li>
                        ))}
                      </ul>
                    )}
                  </div>
                )}

                {/* Confirm Password */}
                <div>
                  <label htmlFor="confirm_password" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Confirm New Password
                  </label>
                  <div className="relative">
                    <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                    <input
                      type={showPasswords.confirm ? 'text' : 'password'}
                      id="confirm_password"
                      value={passwordForm.confirm_password}
                      onChange={(e) => handlePasswordChange('confirm_password', e.target.value)}
                      className={`w-full pl-10 pr-10 py-2 border rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors ${
                        passwordForm.confirm_password && passwordForm.new_password !== passwordForm.confirm_password
                          ? 'border-red-500 dark:border-red-500'
                          : 'border-gray-300 dark:border-gray-600'
                      }`}
                      placeholder="Confirm your new password"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPasswords(prev => ({ ...prev, confirm: !prev.confirm }))}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    >
                      {showPasswords.confirm ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                    </button>
                  </div>
                  {passwordForm.confirm_password && passwordForm.new_password !== passwordForm.confirm_password && (
                    <p className="mt-1 text-xs text-red-600 dark:text-red-400">Passwords do not match</p>
                  )}
                </div>

                {/* Submit button */}
                <div className="flex justify-end pt-4">
                  <button
                    type="submit"
                    disabled={isChangingPassword || !passwordForm.current_password || !passwordForm.new_password || !passwordForm.confirm_password || passwordForm.new_password !== passwordForm.confirm_password || passwordErrors.length > 0}
                    className="inline-flex items-center px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isChangingPassword ? (
                      <>
                        <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                        Changing Password...
                      </>
                    ) : (
                      <>
                        <Key className="h-4 w-4 mr-2" />
                        Change Password
                      </>
                    )}
                  </button>
                </div>
              </div>
            </form>
          </div>

          {/* Security Tips */}
          <div className="lg:col-span-1">
            <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 border border-gray-200 dark:border-gray-700">
              <h3 className="text-sm font-semibold text-gray-900 dark:text-white mb-4">Password Requirements</h3>
              
              <ul className="space-y-3">
                <li className="flex items-start space-x-2">
                  <CheckCircle2 className={`h-4 w-4 ${passwordForm.new_password?.length >= 8 ? 'text-green-500' : 'text-gray-300 dark:text-gray-600'}`} />
                  <span className="text-xs text-gray-600 dark:text-gray-400">At least 8 characters long</span>
                </li>
                <li className="flex items-start space-x-2">
                  <CheckCircle2 className={`h-4 w-4 ${/[A-Z]/.test(passwordForm.new_password) ? 'text-green-500' : 'text-gray-300 dark:text-gray-600'}`} />
                  <span className="text-xs text-gray-600 dark:text-gray-400">At least one uppercase letter</span>
                </li>
                <li className="flex items-start space-x-2">
                  <CheckCircle2 className={`h-4 w-4 ${/[a-z]/.test(passwordForm.new_password) ? 'text-green-500' : 'text-gray-300 dark:text-gray-600'}`} />
                  <span className="text-xs text-gray-600 dark:text-gray-400">At least one lowercase letter</span>
                </li>
                <li className="flex items-start space-x-2">
                  <CheckCircle2 className={`h-4 w-4 ${/[0-9]/.test(passwordForm.new_password) ? 'text-green-500' : 'text-gray-300 dark:text-gray-600'}`} />
                  <span className="text-xs text-gray-600 dark:text-gray-400">At least one number</span>
                </li>
                <li className="flex items-start space-x-2">
                  <CheckCircle2 className={`h-4 w-4 ${/[^A-Za-z0-9]/.test(passwordForm.new_password) ? 'text-green-500' : 'text-gray-300 dark:text-gray-600'}`} />
                  <span className="text-xs text-gray-600 dark:text-gray-400">At least one special character</span>
                </li>
              </ul>

              <div className="mt-6 pt-6 border-t border-gray-200 dark:border-gray-700">
                <h3 className="text-sm font-semibold text-gray-900 dark:text-white mb-2">Security Tips</h3>
                <ul className="space-y-2 text-xs text-gray-600 dark:text-gray-400">
                  <li>• Use a unique password for each account</li>
                  <li>• Avoid using personal information</li>
                  <li>• Enable two-factor authentication</li>
                  <li>• Change your password regularly</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 2FA Tab */}
      {activeTab === '2fa' && (
        <div className="max-w-2xl">
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 border border-gray-200 dark:border-gray-700">
            <div className="flex items-start justify-between mb-6">
              <div>
                <h2 className="text-lg font-semibold text-gray-900 dark:text-white">Two-Factor Authentication</h2>
                <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                  Add an extra layer of security to your account
                </p>
              </div>
              <Shield className={`h-8 w-8 ${profile?.two_factor_enabled ? 'text-green-500' : 'text-gray-400'}`} />
            </div>

            {/* Current Status */}
            <div className={`p-4 rounded-lg mb-6 ${
              profile?.two_factor_enabled 
                ? 'bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800'
                : 'bg-gray-50 dark:bg-gray-700/50 border border-gray-200 dark:border-gray-700'
            }`}>
              <div className="flex items-center">
                {profile?.two_factor_enabled ? (
                  <CheckCircle2 className="h-5 w-5 text-green-500 mr-3" />
                ) : (
                  <AlertCircle className="h-5 w-5 text-gray-400 mr-3" />
                )}
                <div>
                  <p className={`text-sm font-medium ${
                    profile?.two_factor_enabled 
                      ? 'text-green-800 dark:text-green-300'
                      : 'text-gray-900 dark:text-white'
                  }`}>
                    {profile?.two_factor_enabled ? '2FA is enabled' : '2FA is disabled'}
                  </p>
                  <p className={`text-xs ${
                    profile?.two_factor_enabled 
                      ? 'text-green-600 dark:text-green-400'
                      : 'text-gray-500 dark:text-gray-400'
                  }`}>
                    {profile?.two_factor_enabled 
                      ? 'Your account is protected with email-based 2FA'
                      : 'Enable 2FA to better protect your account'
                    }
                  </p>
                </div>
              </div>
            </div>

            {/* 2FA Method Selection */}
            {!profile?.two_factor_enabled && !show2FAInput && (
              <div className="space-y-4">
                <h3 className="text-sm font-medium text-gray-900 dark:text-white">Choose your 2FA method</h3>
                
                <div className="border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer transition-colors">
                  <div className="flex items-center">
                    <div className="flex-1 flex items-center">
                      <MailIcon className="h-5 w-5 text-blue-500 mr-3" />
                      <div>
                        <p className="text-sm font-medium text-gray-900 dark:text-white">Email Authentication</p>
                        <p className="text-xs text-gray-500 dark:text-gray-400">
                          Receive verification codes via email
                        </p>
                      </div>
                    </div>
                    <div className="w-5 h-5 rounded-full border-2 border-blue-500 flex items-center justify-center">
                      <div className="w-2.5 h-2.5 bg-blue-500 rounded-full"></div>
                    </div>
                  </div>
                </div>

                <button
                  onClick={handleToggle2FA}
                  disabled={isToggling2FA || !profile?.email_verified}
                  className="w-full mt-4 inline-flex items-center justify-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isToggling2FA ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      Sending Code...
                    </>
                  ) : (
                    <>
                      <Shield className="h-4 w-4 mr-2" />
                      Enable 2FA
                    </>
                  )}
                </button>

                {!profile?.email_verified && (
                  <p className="text-xs text-yellow-600 dark:text-yellow-400 text-center">
                    Please verify your email before enabling 2FA
                  </p>
                )}
              </div>
            )}

            {/* 2FA Code Input */}
            {show2FAInput && (
              <div className="space-y-4">
                <p className="text-sm text-gray-600 dark:text-gray-400">
                  Enter the 6-digit code sent to <span className="font-medium text-gray-900 dark:text-white">{profile?.email}</span>
                </p>

                <div>
                  <label htmlFor="2fa_code" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Verification Code
                  </label>
                  <div className="relative">
                    <Smartphone className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                    <input
                      type="text"
                      id="2fa_code"
                      value={twoFACode}
                      onChange={(e) => setTwoFACode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                      className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                      placeholder="Enter 6-digit code"
                      maxLength={6}
                    />
                  </div>
                </div>

                <div className="flex items-center justify-between">
                  <button
                    type="button"
                    onClick={resend2FACode}
                    disabled={countdown > 0}
                    className="text-sm text-blue-600 hover:text-blue-700 dark:text-blue-400 disabled:text-gray-400 disabled:cursor-not-allowed"
                  >
                    Resend code {countdown > 0 && `(${countdown}s)`}
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      setShow2FAInput(false);
                      setTwoFACode('');
                    }}
                    className="text-sm text-gray-600 hover:text-gray-700 dark:text-gray-400"
                  >
                    Cancel
                  </button>
                </div>

                <button
                  onClick={verify2FACode}
                  disabled={isVerifying2FA || twoFACode.length !== 6}
                  className="w-full inline-flex items-center justify-center px-4 py-2 bg-green-600 hover:bg-green-700 text-white font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isVerifying2FA ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      Verifying...
                    </>
                  ) : (
                    <>
                      <CheckCircle2 className="h-4 w-4 mr-2" />
                      Verify & Enable 2FA
                    </>
                  )}
                </button>
              </div>
            )}

            {/* Disable 2FA */}
            {profile?.two_factor_enabled && (
              <div className="mt-6 pt-6 border-t border-gray-200 dark:border-gray-700">
                <h3 className="text-sm font-medium text-gray-900 dark:text-white mb-3">Disable Two-Factor Authentication</h3>
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
                  Once disabled, your account will no longer require a verification code during login.
                </p>
                <button
                  onClick={handleToggle2FA}
                  disabled={isToggling2FA}
                  className="inline-flex items-center px-4 py-2 bg-red-600 hover:bg-red-700 text-white font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isToggling2FA ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      Disabling...
                    </>
                  ) : (
                    <>
                      <X className="h-4 w-4 mr-2" />
                      Disable 2FA
                    </>
                  )}
                </button>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}