// app/components/admin/profile/ProfileForm.tsx
'use client';

import { useState, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import Image from 'next/image';
import { useUserStore } from '@/stores/admin-store';

interface UserData {
  id: string;
  email: string;
  first_name: string;
  last_name: string;
  avatar_url?: string;
  is_2fa_enabled: boolean;
  phone?: string;
  created_at: string;
  two_factor_method: 'email' | 'totp' | 'none';
  totp_verified: boolean;
  backup_codes?: string[];
}

interface ProfileFormData {
  first_name: string;
  last_name: string;
  phone: string;
  avatar_url: string;
  is_2fa_enabled: boolean;
}

interface PasswordFormData {
  current_password: string;
  new_password: string;
  confirm_password: string;
}

interface TotpSetupData {
  secret: string;
  otpauthUrl: string;
  qrCodeDataUrl: string;
  backupCodes: string[];
}

export default function ProfileForm() {
  const router = useRouter();
  const { user: globalUser, updateUser } = useUserStore();
  const [loading, setLoading] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [changingPassword, setChangingPassword] = useState(false);
  const [userData, setUserData] = useState<UserData | null>(null);
  const [activeTab, setActiveTab] = useState<'profile' | 'password' | '2fa'>('profile');
  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [twoFactorMethod, setTwoFactorMethod] = useState<'email' | 'totp' | 'none'>('email');
  const [totpSetupData, setTotpSetupData] = useState<TotpSetupData | null>(null);
  const [totpVerificationCode, setTotpVerificationCode] = useState('');
  const [showBackupCodes, setShowBackupCodes] = useState(false);
  const [showRemoveAuthenticator, setShowRemoveAuthenticator] = useState(false);
  const [removePassword, setRemovePassword] = useState('');
  const [confirmRemovePassword, setConfirmRemovePassword] = useState('');
  const [showRemovePassword, setShowRemovePassword] = useState(false);
  const [showConfirmRemovePassword, setShowConfirmRemovePassword] = useState(false);
  const [saving2FA, setSaving2FA] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const [profileFormData, setProfileFormData] = useState<ProfileFormData>({
    first_name: '',
    last_name: '',
    phone: '',
    avatar_url: '',
    is_2fa_enabled: false
  });

  const [passwordFormData, setPasswordFormData] = useState<PasswordFormData>({
    current_password: '',
    new_password: '',
    confirm_password: ''
  });

  // Fetch user data
  useEffect(() => {
    const fetchUserData = async () => {
      try {
        const response = await fetch('/api/backend/admin/profile');
        if (response.ok) {
          const data = await response.json();
          setUserData(data.user);
          setProfileFormData({
            first_name: data.user.first_name || '',
            last_name: data.user.last_name || '',
            phone: data.user.phone || '',
            avatar_url: data.user.avatar_url || '',
            is_2fa_enabled: data.user.is_2fa_enabled || false
          });
          setTwoFactorMethod(data.user.two_factor_method || 'email');
        } else {
          const error = await response.json();
          toast.error(error.error || 'Failed to load profile data');
        }
      } catch (error) {
        console.error('Failed to load profile data:', error);
        toast.error('Failed to load profile data');
      }
    };

    fetchUserData();
  }, []);

  const handleProfileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type } = e.target;
    setProfileFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? (e.target as HTMLInputElement).checked : value
    }));
  };

  const handlePasswordInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setPasswordFormData(prev => ({ ...prev, [name]: value }));
  };

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);

    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('type', 'avatar');

      const response = await fetch('/api/backend/admin/upload', {
        method: 'POST',
        body: formData,
      });

      const data = await response.json();

      if (data.success) {
        setProfileFormData(prev => ({ ...prev, avatar_url: data.url }));
        toast.success('Avatar uploaded successfully');
      } else {
        toast.error(data.error || 'Failed to upload avatar');
      }
    } catch (error) {
      console.error('Avatar upload error:', error);
      toast.error('Failed to upload avatar');
    } finally {
      setUploading(false);
    }
  };

  const removeImage = async () => {
    if (!profileFormData.avatar_url) return;

    try {
      const response = await fetch('/api/backend/admin/upload', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ url: profileFormData.avatar_url }),
      });
      const data = await response.json();
      if (!data.success) console.warn('Failed to delete avatar:', data.error);
    } catch (error) {
      console.error('Error deleting avatar:', error);
    } finally {
      setProfileFormData(prev => ({ ...prev, avatar_url: '' }));
      if (fileInputRef.current) fileInputRef.current.value = '';
      toast.success('Avatar removed');
    }
  };

  const downloadBackupCodes = (codes: string[]) => {
    const content = `Google Authenticator Backup Codes\n\n` +
      `Account: ${userData?.email}\n` +
      `Generated: ${new Date().toLocaleString()}\n\n` +
      `IMPORTANT: Each code can only be used once. Keep these codes in a safe place.\n\n` +
      `Backup Codes:\n${codes.map((code, i) => `${i + 1}. ${code}`).join('\n')}\n\n` +
      `Instructions:\n` +
      `1. Save this file in a secure location\n` +
      `2. Use these codes if you lose access to your authenticator app\n` +
      `3. Each code works only once\n` +
      `4. Generate new backup codes if you use all of these`;

    const blob = new Blob([content], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `backup-codes-${userData?.email?.split('@')[0] || 'account'}-${new Date().toISOString().split('T')[0]}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    toast.success('Backup codes downloaded');
  };

  const validateProfileForm = (): boolean => {
    if (!profileFormData.first_name.trim()) {
      toast.error('First name is required');
      return false;
    }
    if (!profileFormData.last_name.trim()) {
      toast.error('Last name is required');
      return false;
    }
    return true;
  };

  const validatePasswordForm = (): boolean => {
    if (!passwordFormData.current_password) {
      toast.error('Current password is required');
      return false;
    }
    if (!passwordFormData.new_password) {
      toast.error('New password is required');
      return false;
    }
    if (!passwordFormData.confirm_password) {
      toast.error('Confirm password is required');
      return false;
    }
    if (passwordFormData.new_password !== passwordFormData.confirm_password) {
      toast.error('New passwords do not match');
      return false;
    }
    if (passwordFormData.new_password.length < 8) {
      toast.error('Password must be at least 8 characters long');
      return false;
    }
    return true;
  };

  const handleProfileSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validateProfileForm()) return;

    setLoading(true);

    try {
      const response = await fetch('/api/backend/admin/profile', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(profileFormData),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success('Profile updated successfully');
        if (globalUser) {
          updateUser({
            first_name: profileFormData.first_name,
            last_name: profileFormData.last_name,
            avatar_url: profileFormData.avatar_url
          });
        }
        const userResponse = await fetch('/api/backend/admin/profile');
        if (userResponse.ok) {
          const userData = await userResponse.json();
          setUserData(userData.user);
        }
      } else {
        toast.error(data.error || 'Failed to update profile');
      }
    } catch (error) {
      console.error('Error:', error);
      toast.error('Failed to update profile');
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validatePasswordForm()) return;

    setChangingPassword(true);

    try {
      const response = await fetch('/api/backend/admin/profile', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(passwordFormData),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success('Password changed successfully');
        setPasswordFormData({
          current_password: '',
          new_password: '',
          confirm_password: ''
        });
        setShowCurrentPassword(false);
        setShowNewPassword(false);
        setShowConfirmPassword(false);
      } else {
        toast.error(data.error || 'Failed to change password');
      }
    } catch (error) {
      console.error('Error:', error);
      toast.error('Failed to change password');
    } finally {
      setChangingPassword(false);
    }
  };

  const handleGenerateTotp = async () => {
    try {
      const response = await fetch('/api/backend/admin/profile', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'generate-totp-secret' }),
      });

      const data = await response.json();

      if (response.ok) {
        setTotpSetupData({
          secret: data.secret,
          otpauthUrl: data.otpauthUrl,
          qrCodeDataUrl: data.qrCodeDataUrl,
          backupCodes: []
        });
        setTotpVerificationCode('');
        toast.success('TOTP secret generated. Scan the QR code with Google Authenticator.');
      } else {
        toast.error(data.error || 'Failed to generate TOTP secret');
      }
    } catch (error) {
      console.error('Error generating TOTP:', error);
      toast.error('Failed to generate TOTP secret');
    }
  };

  const handleVerifyTotp = async () => {
    if (!totpVerificationCode.trim()) {
      toast.error('Please enter the verification code');
      return;
    }

    try {
      const response = await fetch('/api/backend/admin/profile', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'verify-totp',
          token: totpVerificationCode
        }),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success('TOTP verified successfully!');
        setTotpSetupData(prev => prev ? { ...prev, backupCodes: data.backupCodes || [] } : null);
        setTotpVerificationCode('');
        setShowBackupCodes(true);
        const userResponse = await fetch('/api/backend/admin/profile');
        if (userResponse.ok) {
          const userData = await userResponse.json();
          setUserData(userData.user);
          setTwoFactorMethod(userData.user.two_factor_method);
        }
      } else {
        toast.error(data.error || 'Invalid verification code');
      }
    } catch (error) {
      console.error('Error verifying TOTP:', error);
      toast.error('Failed to verify TOTP');
    }
  };

  const handleSwitch2FAMethod = async (method: 'email' | 'totp') => {
    if (method === 'totp' && userData && !userData.totp_verified) {
      toast.error('Please set up TOTP first');
      return;
    }

    try {
      const response = await fetch('/api/backend/admin/profile', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'switch-method', method }),
      });

      const data = await response.json();

      if (response.ok) {
        setTwoFactorMethod(method);
        toast.success(`2FA method switched to ${method === 'email' ? 'Email OTP' : 'Google Authenticator'}`);
        const userResponse = await fetch('/api/backend/admin/profile');
        if (userResponse.ok) {
          const userData = await userResponse.json();
          setUserData(userData.user);
        }
      } else {
        toast.error(data.error || 'Failed to switch 2FA method');
      }
    } catch (error) {
      console.error('Error switching 2FA method:', error);
      toast.error('Failed to switch 2FA method');
    }
  };

  const handleRemoveTotp = async () => {
    if (!removePassword) {
      toast.error('Please enter your password');
      return;
    }
    if (removePassword !== confirmRemovePassword) {
      toast.error('Passwords do not match');
      return;
    }

    try {
      const response = await fetch('/api/backend/admin/profile', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'disable-totp', password: removePassword }),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success('Google Authenticator removed successfully');
        setTwoFactorMethod('email');
        setTotpSetupData(null);
        setShowRemoveAuthenticator(false);
        setRemovePassword('');
        setConfirmRemovePassword('');
        const userResponse = await fetch('/api/backend/admin/profile');
        if (userResponse.ok) {
          const userData = await userResponse.json();
          setUserData(userData.user);
        }
      } else {
        toast.error(data.error || 'Failed to remove Google Authenticator');
      }
    } catch (error) {
      console.error('Error removing TOTP:', error);
      toast.error('Failed to remove Google Authenticator');
    }
  };

  const handleSave2FASettings = async () => {
    setSaving2FA(true);

    try {
      const response = await fetch('/api/backend/admin/profile', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'update-2fa-settings',
          is_2fa_enabled: profileFormData.is_2fa_enabled
        }),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success('2FA settings updated successfully');
        const userResponse = await fetch('/api/backend/admin/profile');
        if (userResponse.ok) {
          const userData = await userResponse.json();
          setUserData(userData.user);
          setProfileFormData(prev => ({ ...prev, is_2fa_enabled: userData.user.is_2fa_enabled }));
          setTwoFactorMethod(userData.user.two_factor_method);
        }
      } else {
        toast.error(data.error || 'Failed to update 2FA settings');
      }
    } catch (error) {
      console.error('Error saving 2FA settings:', error);
      toast.error('Failed to update 2FA settings');
    } finally {
      setSaving2FA(false);
    }
  };

  return (
    <div className="max-w-6xl mx-auto">
      <div className="bg-var-surface rounded-2xl shadow-var-card border border-var-border overflow-hidden">
        {/* Header */}
        <div className="px-6 py-4 border-b border-var-border bg-linear-to-r from-var-surface-hover to-var-surface">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-xl font-semibold text-var-text">Profile Settings</h2>
              <p className="text-sm text-var-text-secondary mt-1">
                Manage your account information and security settings
              </p>
            </div>
            <div className="flex items-center space-x-4">
              {userData && (
                <div className="text-right">
                  <p className="text-sm font-medium text-var-text">
                    {userData.first_name} {userData.last_name}
                  </p>
                  <p className="text-sm text-var-text-muted">{userData.email}</p>
                </div>
              )}
              <div className="relative">
                {profileFormData.avatar_url ? (
                  <Image
                    src={profileFormData.avatar_url}
                    alt="Avatar"
                    className="w-10 h-10 rounded-full object-cover border-2 border-var-surface shadow-var-card"
                    width={40}
                    height={40}
                  />
                ) : (
                  <div className="w-10 h-10 rounded-full bg-var-primary flex items-center justify-center text-white font-semibold">
                    {profileFormData.first_name?.[0]}
                    {profileFormData.last_name?.[0]}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Tabs */}
        <div className="border-b border-var-border">
          <nav className="flex px-6" aria-label="Tabs">
            <button
              onClick={() => setActiveTab('profile')}
              className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors duration-200 ${
                activeTab === 'profile'
                  ? 'border-var-primary text-var-primary'
                  : 'border-transparent text-var-text-muted hover:text-var-text hover:border-var-border'
              }`}
            >
              Profile Information
            </button>
            <button
              onClick={() => setActiveTab('password')}
              className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors duration-200 ${
                activeTab === 'password'
                  ? 'border-var-primary text-var-primary'
                  : 'border-transparent text-var-text-muted hover:text-var-text hover:border-var-border'
              }`}
            >
              Change Password
            </button>
            <button
              onClick={() => setActiveTab('2fa')}
              className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors duration-200 ${
                activeTab === '2fa'
                  ? 'border-var-primary text-var-primary'
                  : 'border-transparent text-var-text-muted hover:text-var-text hover:border-var-border'
              }`}
            >
              Two-Factor Auth
            </button>
          </nav>
        </div>

        {/* Content */}
        <div className="p-6">
          {activeTab === 'profile' ? (
            <form onSubmit={handleProfileSubmit} className="space-y-8">
              {/* Personal Information */}
              <div>
                <h3 className="text-lg font-medium text-var-text mb-4">Personal Information</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label htmlFor="first_name" className="block text-sm font-medium text-var-text mb-2">
                      First Name *
                    </label>
                    <input
                      type="text"
                      id="first_name"
                      name="first_name"
                      value={profileFormData.first_name}
                      onChange={handleProfileInputChange}
                      required
                      className="w-full px-3 py-2 bg-var-input border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary transition-colors text-var-text placeholder-var-input"
                      placeholder="Enter your first name"
                    />
                  </div>

                  <div>
                    <label htmlFor="last_name" className="block text-sm font-medium text-var-text mb-2">
                      Last Name *
                    </label>
                    <input
                      type="text"
                      id="last_name"
                      name="last_name"
                      value={profileFormData.last_name}
                      onChange={handleProfileInputChange}
                      required
                      className="w-full px-3 py-2 bg-var-input border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary transition-colors text-var-text placeholder-var-input"
                      placeholder="Enter your last name"
                    />
                  </div>

                  <div>
                    <label htmlFor="phone" className="block text-sm font-medium text-var-text mb-2">
                      Phone Number
                    </label>
                    <input
                      type="tel"
                      id="phone"
                      name="phone"
                      value={profileFormData.phone}
                      onChange={handleProfileInputChange}
                      className="w-full px-3 py-2 bg-var-input border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary transition-colors text-var-text placeholder-var-input"
                      placeholder="+1 (555) 123-4567"
                    />
                  </div>

                  <div>
                    <label htmlFor="email" className="block text-sm font-medium text-var-text mb-2">
                      Email Address
                    </label>
                    <input
                      type="email"
                      id="email"
                      value={userData?.email || ''}
                      disabled
                      className="w-full px-3 py-2 bg-var-input border border-var-border rounded-xl text-var-text-muted cursor-not-allowed"
                    />
                    <p className="text-sm text-var-text-muted mt-2">Email address cannot be changed</p>
                  </div>
                </div>
              </div>

              {/* Profile Avatar */}
              <div>
                <h3 className="text-lg font-medium text-var-text mb-4">Profile Picture</h3>
                <div className="flex items-start space-x-6">
                  <div className="shrink-0">
                    <div className="relative">
                      {profileFormData.avatar_url ? (
                        <>
                          <Image
                            src={profileFormData.avatar_url}
                            alt="Profile"
                            className="w-32 h-32 rounded-2xl object-cover border-2 border-var-border"
                            width={128}
                            height={128}
                          />
                          <button
                            type="button"
                            onClick={removeImage}
                            className="absolute -top-2 -right-2 bg-var-danger text-white rounded-full p-1 hover:bg-var-danger-hover transition-colors"
                          >
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                            </svg>
                          </button>
                        </>
                      ) : (
                        <div className="w-32 h-32 rounded-2xl bg-var-surface-hover border-2 border-dashed border-var-border flex items-center justify-center">
                          <div className="text-center">
                            <div className="w-16 h-16 mx-auto rounded-full bg-var-primary flex items-center justify-center text-white text-2xl font-semibold mb-2">
                              {profileFormData.first_name?.[0]}
                              {profileFormData.last_name?.[0]}
                            </div>
                            <p className="text-sm text-var-text-muted">No image</p>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>

                  <div className="flex-1">
                    <label htmlFor="avatar" className="block text-sm font-medium text-var-text mb-2">
                      Upload Profile Picture
                    </label>
                    <input
                      ref={fileInputRef}
                      type="file"
                      id="avatar"
                      accept="image/*"
                      onChange={handleImageUpload}
                      disabled={uploading}
                      className="block w-full text-sm text-var-text-muted file:mr-4 file:py-2 file:px-4 file:rounded-xl file:border-0 file:text-sm file:font-medium file:bg-var-primary-muted file:text-var-primary hover:file:bg-var-primary-muted/70 disabled:opacity-50 disabled:cursor-not-allowed"
                    />
                    <p className="text-sm text-var-text-muted mt-2">
                      JPG, PNG, or WebP. Max 5MB. Recommended: 400x400 pixels.
                    </p>
                    {uploading && (
                      <div className="flex items-center mt-2 text-sm text-var-primary">
                        <svg className="animate-spin -ml-1 mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                        </svg>
                        Uploading...
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Form Actions */}
              <div className="flex items-center justify-end space-x-4 pt-6 border-t border-var-border">
                <button
                  type="button"
                  onClick={() => router.back()}
                  className="px-6 py-2 text-sm font-medium text-var-text-secondary bg-var-surface border border-var-border rounded-xl hover:bg-var-surface-hover transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={loading || uploading}
                  className="inline-flex items-center px-4 py-2 bg-var-primary text-white font-medium rounded-xl hover:bg-var-primary-hover transition-all duration-200 shadow-var-button hover:shadow-var-card"
                >
                  {loading ? (
                    <>
                      <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                      </svg>
                      Saving...
                    </>
                  ) : (
                    'Save Changes'
                  )}
                </button>
              </div>
            </form>
          ) : activeTab === 'password' ? (
            <form onSubmit={handlePasswordSubmit} className="space-y-8">
              {/* Password Change */}
              <div>
                <h3 className="text-lg font-medium text-var-text mb-4">Change Password</h3>
                <div className="space-y-6 max-w-2xl">
                  {/* Current Password */}
                  <div>
                    <label htmlFor="current_password" className="block text-sm font-medium text-var-text mb-2">
                      Current Password *
                    </label>
                    <div className="relative">
                      <input
                        type={showCurrentPassword ? "text" : "password"}
                        id="current_password"
                        name="current_password"
                        value={passwordFormData.current_password}
                        onChange={handlePasswordInputChange}
                        required
                        className="w-full px-3 py-2 bg-var-input border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary transition-colors text-var-text placeholder-var-input pr-10"
                        placeholder="Enter your current password"
                      />
                      <button
                        type="button"
                        onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                        className="absolute inset-y-0 right-0 pr-3 flex items-center text-var-text-muted hover:text-var-text focus:outline-none"
                      >
                        {showCurrentPassword ? (
                          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L6.59 6.59m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                          </svg>
                        ) : (
                          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                          </svg>
                        )}
                      </button>
                    </div>
                  </div>

                  {/* New Password */}
                  <div>
                    <label htmlFor="new_password" className="block text-sm font-medium text-var-text mb-2">
                      New Password *
                    </label>
                    <div className="relative">
                      <input
                        type={showNewPassword ? "text" : "password"}
                        id="new_password"
                        name="new_password"
                        value={passwordFormData.new_password}
                        onChange={handlePasswordInputChange}
                        required
                        className="w-full px-3 py-2 bg-var-input border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary transition-colors text-var-text placeholder-var-input pr-10"
                        placeholder="Enter new password"
                      />
                      <button
                        type="button"
                        onClick={() => setShowNewPassword(!showNewPassword)}
                        className="absolute inset-y-0 right-0 pr-3 flex items-center text-var-text-muted hover:text-var-text focus:outline-none"
                      >
                        {showNewPassword ? (
                          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L6.59 6.59m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                          </svg>
                        ) : (
                          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                          </svg>
                        )}
                      </button>
                    </div>
                    <p className="text-sm text-var-text-muted mt-2">
                      Must be at least 8 characters long
                    </p>
                  </div>

                  {/* Confirm Password */}
                  <div>
                    <label htmlFor="confirm_password" className="block text-sm font-medium text-var-text mb-2">
                      Confirm New Password *
                    </label>
                    <div className="relative">
                      <input
                        type={showConfirmPassword ? "text" : "password"}
                        id="confirm_password"
                        name="confirm_password"
                        value={passwordFormData.confirm_password}
                        onChange={handlePasswordInputChange}
                        required
                        className="w-full px-3 py-2 bg-var-input border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary transition-colors text-var-text placeholder-var-input pr-10"
                        placeholder="Confirm new password"
                      />
                      <button
                        type="button"
                        onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                        className="absolute inset-y-0 right-0 pr-3 flex items-center text-var-text-muted hover:text-var-text focus:outline-none"
                      >
                        {showConfirmPassword ? (
                          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L6.59 6.59m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                          </svg>
                        ) : (
                          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                          </svg>
                        )}
                      </button>
                    </div>
                  </div>
                </div>
              </div>

              {/* Form Actions */}
              <div className="flex items-center justify-end space-x-4 pt-6 border-t border-var-border">
                <button
                  type="button"
                  onClick={() => setActiveTab('profile')}
                  className="px-6 py-2 text-sm font-medium text-var-text-secondary bg-var-surface border border-var-border rounded-xl hover:bg-var-surface-hover transition-colors"
                >
                  Back to Profile
                </button>
                <button
                  type="submit"
                  disabled={changingPassword}
                  className="px-6 py-2 text-sm font-medium text-white bg-var-primary rounded-xl hover:opacity-90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-var-primary disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 shadow-var-button flex items-center gap-2"
                >
                  {changingPassword ? (
                    <>
                      <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                      </svg>
                      Changing...
                    </>
                  ) : (
                    'Change Password'
                  )}
                </button>
              </div>
            </form>
          ) : (
            /* 2FA Settings Tab */
            <div className="space-y-8">
              <div>
                <h3 className="text-lg font-medium text-var-text mb-4">Two-Factor Authentication</h3>

                {/* Current 2FA Status */}
                <div className="mb-8">
                  <div className="flex items-center justify-between p-4 border border-var-border rounded-xl bg-var-surface-hover mb-4">
                    <div>
                      <h4 className="font-medium text-var-text">Two-Factor Status</h4>
                      <p className="text-sm text-var-text-muted mt-1">
                        {userData?.is_2fa_enabled
                          ? `Currently using ${twoFactorMethod === 'email' ? 'Email OTP' : 'Google Authenticator'}`
                          : '2FA is currently disabled'}
                      </p>
                    </div>
                    <div className="flex items-center">
                      <input
                        type="checkbox"
                        id="is_2fa_enabled"
                        name="is_2fa_enabled"
                        checked={profileFormData.is_2fa_enabled}
                        onChange={handleProfileInputChange}
                        className="w-4 h-4 text-var-primary border-var-border rounded focus:ring-var-primary"
                      />
                      <label htmlFor="is_2fa_enabled" className="ml-3 block text-sm font-medium text-var-text">
                        {profileFormData.is_2fa_enabled ? 'Enabled' : 'Disabled'}
                      </label>
                    </div>
                  </div>

                  {/* TOTP Setup Section */}
                  {totpSetupData && !userData?.totp_verified && (
                    <div className="mb-8 p-6 border border-var-info-border rounded-2xl bg-var-info-bg">
                      <div className="flex justify-between items-center mb-4">
                        <h4 className="text-lg font-semibold text-var-info-text">Set Up Google Authenticator</h4>
                        <button
                          onClick={() => {
                            setTotpSetupData(null);
                            setTotpVerificationCode('');
                          }}
                          className="text-sm text-var-info-text hover:text-var-info-hover"
                        >
                          Cancel Setup
                        </button>
                      </div>

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                          <p className="text-sm text-var-info-text mb-3">Scan this QR code with Google Authenticator:</p>
                          <div className="bg-var-surface p-4 rounded-xl inline-block">
                            <Image
                              src={totpSetupData.qrCodeDataUrl}
                              alt="QR Code"
                              width={200}
                              height={200}
                              className="w-48 h-48"
                            />
                          </div>
                          <p className="text-xs text-var-info-text mt-3">
                            Can`t scan? Enter this code manually: <br />
                            <code className="font-mono bg-var-surface px-2 py-1 rounded">{totpSetupData.secret}</code>
                          </p>
                        </div>

                        <div>
                          <p className="text-sm text-var-info-text mb-3">Enter the 6-digit code from Google Authenticator:</p>
                          <div className="space-y-4">
                            <input
                              type="text"
                              value={totpVerificationCode}
                              onChange={(e) => setTotpVerificationCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                              placeholder="000000"
                              className="w-full px-3 py-2 border border-var-info-border rounded-xl text-2xl text-center font-mono tracking-widest focus:ring-2 focus:ring-var-info focus:border-var-info bg-var-input text-var-text"
                              maxLength={6}
                            />
                            <button
                              onClick={handleVerifyTotp}
                              className="w-full px-4 py-2 text-sm font-medium text-white bg-var-success rounded-xl hover:bg-var-success-hover"
                            >
                              Verify & Enable
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* Backup Codes Display */}
                  {showBackupCodes && totpSetupData?.backupCodes && totpSetupData.backupCodes.length > 0 && (
                    <div className="mb-8 p-6 border border-var-warning-border rounded-2xl bg-var-warning-bg">
                      <h4 className="text-lg font-semibold text-var-warning-text mb-4 flex items-center">
                        <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                          <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
                        </svg>
                        Save Your Backup Codes
                      </h4>
                      <p className="text-sm text-var-warning-text mb-4">
                        These codes can be used to access your account if you lose your authenticator device.
                        Save them in a safe place. Each code can only be used once.
                      </p>

                      <div className="grid grid-cols-2 md:grid-cols-5 gap-3 mb-6">
                        {totpSetupData.backupCodes.map((code, index) => (
                          <div
                            key={index}
                            className="bg-var-surface border border-var-warning-border rounded-lg p-3 text-center font-mono text-sm text-var-text"
                          >
                            {code}
                          </div>
                        ))}
                      </div>

                      <div className="flex justify-between items-center">
                        <button
                          onClick={() => downloadBackupCodes(totpSetupData.backupCodes)}
                          className="px-4 py-2 text-sm font-medium text-white bg-var-primary rounded-lg hover:bg-var-primary-hover flex items-center gap-2"
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                          </svg>
                          Download Backup Codes
                        </button>
                        <button
                          onClick={() => {
                            setShowBackupCodes(false);
                            setTotpSetupData(null);
                          }}
                          className="px-4 py-2 text-sm font-medium text-var-warning-text bg-var-warning-bg border border-var-warning-border rounded-lg hover:bg-var-warning-bg/70"
                        >
                          I`ve Saved These Codes
                        </button>
                      </div>
                    </div>
                  )}

                  {/* Google Authenticator Section */}
                  <div className="p-4 border border-var-border rounded-xl mb-4">
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center">
                        <div className="p-2 bg-var-success-bg rounded-lg mr-3">
                          <svg className="w-5 h-5 text-var-success" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                          </svg>
                        </div>
                        <div>
                          <h4 className="font-medium text-var-text">Google Authenticator</h4>
                          <p className="text-sm text-var-text-muted">Use authenticator app for 2FA codes</p>
                        </div>
                      </div>

                      <div className="flex items-center space-x-3">
                        {userData?.totp_verified && (
                          <span className="px-3 py-1 text-xs font-medium bg-var-success-bg text-var-success-text rounded-full flex items-center">
                            <svg className="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                              <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                            </svg>
                            Verified
                          </span>
                        )}

                        {userData?.totp_verified ? (
                          <button
                            onClick={handleGenerateTotp}
                            className="px-4 py-1.5 text-sm font-medium text-var-primary bg-var-primary-muted border border-var-primary rounded-lg hover:bg-var-primary-muted/70"
                          >
                            New Setup
                          </button>
                        ) : (
                          <button
                            onClick={handleGenerateTotp}
                            className="px-4 py-1.5 text-sm font-medium text-white bg-var-success rounded-lg hover:bg-var-success-hover"
                          >
                            Set Up
                          </button>
                        )}
                      </div>
                    </div>

                    {userData?.totp_verified && (
                      <div className="mt-4 pt-4 border-t border-var-border">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div>
                            <p className="text-sm font-medium text-var-text">Status</p>
                            <p className="text-sm text-var-success flex items-center">
                              <svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                              </svg>
                              Set up and verified
                            </p>
                          </div>
                          <div>
                            <p className="text-sm font-medium text-var-text">2FA Method</p>
                            <p className="text-sm text-var-text-muted">
                              {twoFactorMethod === 'totp' ? 'Currently active' : 'Set up but not active'}
                            </p>
                          </div>
                        </div>

                        <div className="mt-4 flex flex-wrap gap-2">
                          {twoFactorMethod !== 'totp' && (
                            <button
                              onClick={() => handleSwitch2FAMethod('totp')}
                              className="px-4 py-2 text-sm font-medium text-white bg-var-success rounded-lg hover:bg-var-success-hover"
                            >
                              Switch to Google Authenticator
                            </button>
                          )}

                          {userData?.backup_codes && userData.backup_codes.length > 0 && (
                            <button
                              onClick={() => {
                                setTotpSetupData({
                                  secret: '',
                                  otpauthUrl: '',
                                  qrCodeDataUrl: '',
                                  backupCodes: userData.backup_codes || []
                                });
                                setShowBackupCodes(true);
                              }}
                              className="px-4 py-2 text-sm font-medium text-var-primary bg-var-primary-muted border border-var-primary rounded-lg hover:bg-var-primary-muted/70"
                            >
                              View Backup Codes
                            </button>
                          )}

                          {!showRemoveAuthenticator ? (
                            <button
                              onClick={() => setShowRemoveAuthenticator(true)}
                              className="px-4 py-2 text-sm font-medium text-var-danger bg-var-danger-bg border border-var-danger-border rounded-lg hover:bg-var-danger-bg/70"
                            >
                              Remove Authenticator
                            </button>
                          ) : (
                            <button
                              onClick={() => {
                                setShowRemoveAuthenticator(false);
                                setRemovePassword('');
                                setConfirmRemovePassword('');
                              }}
                              className="px-4 py-2 text-sm font-medium text-var-text-muted bg-var-surface-hover border border-var-border rounded-lg hover:bg-var-surface-hover"
                            >
                              Cancel
                            </button>
                          )}
                        </div>

                        {/* Password Verification Form */}
                        {showRemoveAuthenticator && (
                          <div className="mt-4 p-4 border border-var-danger-border rounded-xl bg-var-danger-bg">
                            <h5 className="text-sm font-medium text-var-danger-text mb-3">Confirm Removal</h5>
                            <p className="text-sm text-var-danger-text mb-4">
                              To remove Google Authenticator, please enter your password to confirm.
                            </p>

                            <div className="space-y-4">
                              <div>
                                <label htmlFor="removePassword" className="block text-sm font-medium text-var-danger-text mb-2">
                                  Current Password *
                                </label>
                                <div className="relative">
                                  <input
                                    type={showRemovePassword ? "text" : "password"}
                                    id="removePassword"
                                    name="disable-password"
                                    value={removePassword}
                                    onChange={(e) => setRemovePassword(e.target.value)}
                                    className="w-full px-3 py-2 bg-var-input border border-var-danger-border rounded-xl focus:ring-2 focus:ring-var-danger focus:border-var-danger text-var-text placeholder-var-input pr-10"
                                    placeholder="Enter your password"
                                  />
                                  <button
                                    type="button"
                                    onClick={() => setShowRemovePassword(!showRemovePassword)}
                                    className="absolute inset-y-0 right-0 pr-3 flex items-center text-var-danger hover:text-var-danger-text focus:outline-none"
                                  >
                                    {showRemovePassword ? (
                                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L6.59 6.59m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                                      </svg>
                                    ) : (
                                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                      </svg>
                                    )}
                                  </button>
                                </div>
                              </div>

                              <div>
                                <label htmlFor="confirmRemovePassword" className="block text-sm font-medium text-var-danger-text mb-2">
                                  Confirm Password *
                                </label>
                                <div className="relative">
                                  <input
                                    type={showConfirmRemovePassword ? "text" : "password"}
                                    id="confirmRemovePassword"
                                    name="confirm-disable-password"
                                    value={confirmRemovePassword}
                                    onChange={(e) => setConfirmRemovePassword(e.target.value)}
                                    className="w-full px-3 py-2 bg-var-input border border-var-danger-border rounded-xl focus:ring-2 focus:ring-var-danger focus:border-var-danger text-var-text placeholder-var-input pr-10"
                                    placeholder="Confirm your password"
                                  />
                                  <button
                                    type="button"
                                    onClick={() => setShowConfirmRemovePassword(!showConfirmRemovePassword)}
                                    className="absolute inset-y-0 right-0 pr-3 flex items-center text-var-danger hover:text-var-danger-text focus:outline-none"
                                  >
                                    {showConfirmRemovePassword ? (
                                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L6.59 6.59m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                                      </svg>
                                    ) : (
                                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                      </svg>
                                    )}
                                  </button>
                                </div>
                              </div>

                              <div className="flex justify-end space-x-3">
                                <button
                                  onClick={() => {
                                    setShowRemoveAuthenticator(false);
                                    setRemovePassword('');
                                    setConfirmRemovePassword('');
                                  }}
                                  className="px-4 py-2 text-sm font-medium text-var-text-secondary bg-var-surface border border-var-border rounded-lg hover:bg-var-surface-hover"
                                >
                                  Cancel
                                </button>
                                <button
                                  onClick={handleRemoveTotp}
                                  disabled={!removePassword || !confirmRemovePassword}
                                  className="px-4 py-2 text-sm font-medium text-white bg-var-danger rounded-lg hover:bg-var-danger-hover disabled:opacity-50 disabled:cursor-not-allowed"
                                >
                                  Remove Authenticator
                                </button>
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    )}
                  </div>

                  {/* Email OTP Method */}
                  <div className="p-4 border border-var-border rounded-xl">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center">
                        <div className="p-2 bg-var-primary-muted rounded-lg mr-3">
                          <svg className="w-5 h-5 text-var-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                          </svg>
                        </div>
                        <div>
                          <h4 className="font-medium text-var-text">Email OTP</h4>
                          <p className="text-sm text-var-text-muted">Receive 6-digit code via email</p>
                        </div>
                      </div>
                      <div className="flex items-center">
                        {twoFactorMethod === 'email' && (
                          <span className="mr-3 text-sm text-var-success font-medium flex items-center">
                            <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            Active
                          </span>
                        )}
                        <button
                          onClick={() => handleSwitch2FAMethod('email')}
                          className={`px-4 py-1.5 text-sm font-medium rounded-lg ${
                            twoFactorMethod === 'email'
                              ? 'bg-var-primary text-white'
                              : 'bg-var-surface-hover text-var-text hover:bg-var-surface-hover'
                          }`}
                          disabled={twoFactorMethod === 'email'}
                        >
                          {twoFactorMethod === 'email' ? 'Active' : 'Switch to Email'}
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* Save 2FA Settings Button */}
              <div className="flex items-center justify-end space-x-4 pt-6 border-t border-var-border">
                <button
                  type="button"
                  onClick={() => setActiveTab('profile')}
                  className="px-6 py-2 text-sm font-medium text-var-text-secondary bg-var-surface border border-var-border rounded-xl hover:bg-var-surface-hover transition-colors"
                >
                  Back to Profile
                </button>
                <button
                  type="button"
                  onClick={handleSave2FASettings}
                  disabled={saving2FA}
                  className="inline-flex items-center px-4 py-2 bg-var-primary text-white font-medium rounded-xl hover:bg-var-primary-hover transition-all duration-200 shadow-var-button hover:shadow-var-card"
                >
                  {saving2FA ? (
                    <>
                      <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                      </svg>
                      Saving...
                    </>
                  ) : (
                    'Save Settings'
                  )}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}