import React, { useState, useEffect, useRef } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
import { 
  User, 
  Mail, 
  Phone, 
  Save, 
  CheckCircle,
  AlertCircle,
  Lock,
  Camera,
  Shield,
  ShieldCheck,
  ShieldOff,
  Copy,
  RefreshCw,
  KeyRound,
  LogOut,
  Monitor,
  FileText,
  Download,
  Trash2,
  Database,
  Smartphone,
  Tablet
} from 'lucide-react';
import { toast } from 'react-toastify';
import authService from '../../features/auth/services/authService';
import sessionService from '../../features/auth/services/sessionService';
import gdprService, { GDPRRequest } from '../../features/compliance/services/gdprService';
import useAuthStore from '../../store/useAuthStore';
import Loading from '../../shared/components/Loading';
import EmptyState from '../../shared/components/EmptyState';
import { useAsync } from '../../shared/hooks/useAsync';
import { useGlobalLoading } from '../../shared/contexts/LoadingContext';
import { normalizeImageUrl } from '../../shared/utils/imageUtils';
import { formatDate } from '../../shared/utils/format';
import { UserSession } from '../../features/auth/services/sessionService';
import { useNavigate } from 'react-router-dom';

const profileValidationSchema = yup.object().shape({
  name: yup
    .string()
    .required('Full name is required')
    .min(2, 'Full name must be at least 2 characters')
    .max(100, 'Full name cannot exceed 100 characters'),
  email: yup
    .string()
    .required('Email is required')
    .email('Invalid email address'),
  phone: yup
    .string()
    .required('Phone number is required')
    .matches(
      /^[\d\s\-+()]{5,}$/,
      'Please enter a valid phone number'
    ),
});

const passwordValidationSchema = yup.object().shape({
  currentPassword: yup
    .string()
    .required('Current password is required'),
  newPassword: yup
    .string()
    .required('New password is required')
    .min(8, 'Password must be at least 8 characters')
    .matches(/[A-Z]/, 'Password must contain at least one uppercase letter')
    .matches(/[a-z]/, 'Password must contain at least one lowercase letter')
    .matches(/[0-9]/, 'Password must contain at least one number')
    .matches(/[!@#$%^&*(),.?":{}|<>]/, 'Password must contain at least one special character (!@#$%^&*(),.?":{}|<>)'),
  confirmPassword: yup
    .string()
    .required('Please confirm your password')
    .oneOf([yup.ref('newPassword')], 'Passwords must match'),
});

type ProfileFormData = yup.InferType<typeof profileValidationSchema>;
type PasswordFormData = yup.InferType<typeof passwordValidationSchema>;

const ProfilePage: React.FC = () => {
  const { userInfo, setUser } = useAuthStore();
  const { setLoading } = useGlobalLoading();
  const _navigate = useNavigate();
  const [activeTab, setActiveTab] = useState<'profile' | 'password' | 'mfa' | 'sessions' | 'gdpr'>('profile');
  const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
  const [avatarError, setAvatarError] = useState<boolean>(false);
  const [showPassword, setShowPassword] = useState<{
    current: boolean;
    new: boolean;
    confirm: boolean;
  }>({
    current: false,
    new: false,
    confirm: false,
  });
  
  
  const [mfaStatus, setMfaStatus] = useState<{mfa_enabled: boolean; backup_codes_count: number} | null>(null);
  const [mfaSecret, setMfaSecret] = useState<string | null>(null);
  const [mfaQrCode, setMfaQrCode] = useState<string | null>(null);
  const [mfaVerificationToken, setMfaVerificationToken] = useState<string>('');
  const [showBackupCodes, setShowBackupCodes] = useState<string[] | null>(null);
  const [showMfaSecret, setShowMfaSecret] = useState<boolean>(false);
  const mfaAbortControllerRef = useRef<AbortController | null>(null);
  const _sessionsAbortControllerRef = useRef<AbortController | null>(null);
  const _gdprAbortControllerRef = useRef<AbortController | null>(null);

  
  const fetchProfile = async () => {
    const response = await authService.getProfile();
    if (response.status === 'success' || response.success) {
      const user = response.data?.user || response.data;
      if (user && typeof user === 'object' && 'id' in user && 'email' in user) {
        setUser(user as { id: number; name: string; email: string; phone?: string; avatar?: string; role: string; createdAt?: string });
        return user;
      }
    }
    throw new Error('Failed to load profile');
  };

  const { 
    data: profileData, 
    loading: loadingProfile, 
    error: profileError,
    execute: refetchProfile 
  } = useAsync(fetchProfile, {
    immediate: true,
    onError: (error: unknown) => {
      toast.error(getUserFriendlyError(error) || 'Unable to load profile');
    }
  });

  
  const {
    register: registerProfile,
    handleSubmit: handleSubmitProfile,
    formState: { errors: profileErrors },
    reset: resetProfile,
  } = useForm<ProfileFormData>({
    resolver: yupResolver(profileValidationSchema),
    defaultValues: {
      name: (userInfo && 'user' in userInfo ? (userInfo.user as { name?: string })?.name : userInfo?.name) || '',
      email: (userInfo && 'user' in userInfo ? (userInfo.user as { email?: string })?.email : userInfo?.email) || '',
      phone: (userInfo && 'user' in userInfo ? (userInfo.user as { phone?: string })?.phone : userInfo?.phone) || '',
    },
  });

  
  const {
    register: registerPassword,
    handleSubmit: handleSubmitPassword,
    formState: { errors: passwordErrors },
    reset: resetPassword,
  } = useForm<PasswordFormData>({
    resolver: yupResolver(passwordValidationSchema),
  });

  
  const fetchMFAStatus = async () => {
    try {
      const response = await authService.getMFAStatus();
      
      if (response) {
        setMfaStatus({
          mfa_enabled: response.mfa_enabled || false,
          backup_codes_count: response.backup_codes_count || 0,
        });
      }
    } catch (error: unknown) {
      const isAbortError = (e: unknown): boolean => {
        if (typeof e === 'object' && e !== null) {
          const err = e as { name?: string; code?: string };
          return err.name === 'AbortError' || err.code === 'ERR_CANCELED';
        }
        return false;
      };
      if (isAbortError(error)) {
        return;
      }
      // Error fetching MFA status - handled silently
    }
  };

  
  useEffect(() => {
    if (profileData || userInfo) {
      const data = profileData || (userInfo && 'user' in userInfo ? userInfo.user : userInfo);
      const userData = data as { name?: string; full_name?: string; email?: string; phone?: string; phone_number?: string; avatar?: string };
      resetProfile({
        name: userData?.name || userData?.full_name || '',
        email: userData?.email || '',
        phone: userData?.phone || userData?.phone_number || '',
      });
      if (userData?.avatar) {
        
        setAvatarPreview(normalizeImageUrl(userData.avatar));
        setAvatarError(false); // Reset error state when new avatar is set
      } else {
        setAvatarPreview(null);
        setAvatarError(false);
      }
    }
  }, [profileData, userInfo, resetProfile]);

  
  useEffect(() => {
    if (activeTab === 'mfa') {
      // Cancel previous request if exists
      if (mfaAbortControllerRef.current) {
        mfaAbortControllerRef.current.abort();
      }

      // Create new abort controller
      mfaAbortControllerRef.current = new AbortController();

      fetchMFAStatus();
    }
    
    // Cleanup: abort request on unmount or tab change
    return () => {
      if (mfaAbortControllerRef.current) {
        mfaAbortControllerRef.current.abort();
      }
    };
  }, [activeTab]);

  
  const onSubmitProfile = async (data: ProfileFormData) => {
    try {
      setLoading(true, 'Updating profile...');
      
      if ('updateProfile' in authService) {
        const response = await authService.updateProfile({
          full_name: data.name,
          email: data.email,
          phone_number: data.phone,
        });

        if (response.status === 'success' || response.success) {
          const updatedUser = response.data?.user || response.data;
          if (updatedUser) {
            setUser(updatedUser);
            toast.success('Profile updated successfully!');
            refetchProfile();
          }
        }
      } else {
        const { updateUser } = await import('../../features/auth/services/userService');
        const user = userInfo && 'user' in userInfo ? userInfo.user : userInfo;
        const userId = (user && typeof user === 'object' && 'id' in user ? (user as { id: number }).id : null) || (userInfo?.id ?? 0);
        const response = await updateUser(userId, {
          full_name: data.name,
          email: data.email,
          phone_number: data.phone,
        });

        if (response.success || (response as { status?: string }).status === 'success') {
          const updatedUser = response.data?.user || response.data;
          if (updatedUser && typeof updatedUser === 'object' && 'id' in updatedUser && 'email' in updatedUser) {
            const userObj = updatedUser as { id: number; email: string; role: string; full_name?: string; name?: string; phone_number?: string; phone?: string; avatar?: string };
            setUser({
              id: userObj.id,
              name: userObj.full_name || userObj.name || '',
              email: userObj.email,
              phone: userObj.phone_number || userObj.phone,
              avatar: userObj.avatar,
              role: userObj.role,
            });
            toast.success('Profile updated successfully!');
            refetchProfile();
          }
        }
      }
    } catch (error: unknown) {
      const errorMessage = 
        getUserFriendlyError(error) || 
        getUserFriendlyError(error) || 
        'Failed to update profile';
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  
  const onSubmitPassword = async (data: PasswordFormData) => {
    try {
      setLoading(true, 'Changing password...');
      
      if ('updateProfile' in authService) {
        const response = await authService.updateProfile({
          currentPassword: data.currentPassword,
          password: data.newPassword,
        });

        if (response.status === 'success' || response.success) {
          toast.success('Password changed successfully!');
          resetPassword();
        }
      } else {
        const { updateUser } = await import('../../features/auth/services/userService');
        const user = userInfo && 'user' in userInfo ? userInfo.user : userInfo;
        const userId = (user && typeof user === 'object' && 'id' in user ? (user as { id: number }).id : null) || (userInfo?.id ?? 0);
        const response = await updateUser(userId, {
          password: data.newPassword,
        });

        if (response.success || (response as { status?: string }).status === 'success') {
          toast.success('Password changed successfully!');
          resetPassword();
        }
      }
    } catch (error: unknown) {
      const errorMessage = 
        getUserFriendlyError(error) || 
        getUserFriendlyError(error) || 
        'Failed to change password';
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  
  const handleAvatarChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    
    if (!file.type.startsWith('image/')) {
      toast.error('Please select an image file');
      return;
    }

    
    if (file.size > 2 * 1024 * 1024) {
      toast.error('Image size must be less than 2MB');
      return;
    }

    
    const reader = new FileReader();
    reader.onloadend = () => {
      setAvatarPreview(reader.result as string);
    };
    reader.readAsDataURL(file);

    
    try {
      setLoading(true, 'Uploading avatar...');
      const response = await authService.uploadAvatar(file);
      
      // Check for success response - backend returns {success: true, status: 'success', data: {...}}
      if ((response.status === 'success' || response.success) && response.data) {
        const updatedUser = response.data.user || response.data;
        const dataObj = response.data as { full_url?: string; avatar_url?: string; user?: { avatar?: string } };
        const avatarUrl = dataObj.full_url || dataObj.avatar_url || normalizeImageUrl((updatedUser && typeof updatedUser === 'object' && 'avatar' in updatedUser ? (updatedUser as { avatar?: string }).avatar : undefined));
        
        if (updatedUser && typeof updatedUser === 'object' && 'id' in updatedUser && 'email' in updatedUser) {
          const userObj = updatedUser as { id: number; email: string; role: string; full_name?: string; name?: string; phone_number?: string; phone?: string; avatar?: string };
          setUser({
            id: userObj.id,
            name: userObj.name || userObj.full_name || '',
            email: userObj.email,
            phone: userObj.phone || userObj.phone_number,
            avatar: avatarUrl,
            role: userObj.role,
          });
          setAvatarPreview(avatarUrl || null);
          setAvatarError(false); // Reset error state on successful upload
          toast.success(response.message || 'Avatar uploaded successfully!');
          refetchProfile();
        } else {
          throw new Error('Invalid response format');
        }
      } else {
        throw new Error(response.message || 'Upload failed');
      }
    } catch (error: unknown) {
      const errorMessage = 
        getUserFriendlyError(error) || 
        getUserFriendlyError(error) ||
        getUserFriendlyError(error) || 
        'Failed to upload avatar. Please try again.';
      toast.error(errorMessage);
      
      // Revert to previous avatar or clear preview on error
      if (userInfo?.avatar) {
        setAvatarPreview(normalizeImageUrl(userInfo.avatar));
        setAvatarError(true); // Set error state so default avatar shows if current one fails
      } else {
        setAvatarPreview(null);
      }
    } finally {
      setLoading(false);
      
      // Clear file input
      e.target.value = '';
    }
  };

  if (loadingProfile) {
    return <Loading fullScreen text="Loading profile..." />;
  }

  if (profileError && !userInfo) {
    return (
      <div className="container mx-auto px-3 sm:px-4 py-4 sm:py-8">
        <EmptyState
          title="Unable to Load Profile"
          description={profileError.message || 'Something went wrong. Please try again.'}
          action={{
            label: 'Retry',
            onClick: refetchProfile
          }}
        />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-slate-100 to-amber-50/30 py-4 sm:py-6 lg:py-8 px-3 sm:px-4 lg:px-8">
      <div className="container mx-auto max-w-6xl">
        {}
        <div className="mb-6 sm:mb-8 animate-fade-in">
          <div className="flex items-center gap-2 sm:gap-3 mb-2 sm:mb-3">
            <div className="h-1 w-12 sm:w-16 md:w-20 bg-gradient-to-r from-[var(--luxury-gold)] via-amber-400 to-[var(--luxury-gold)] rounded-full"></div>
            <h1 className="text-2xl sm:text-3xl lg:text-4xl font-serif font-bold bg-gradient-to-r from-gray-900 via-amber-900/90 to-gray-900 bg-clip-text text-transparent tracking-tight">
              Accountant Profile & Settings
            </h1>
          </div>
          <p className="text-sm sm:text-base text-gray-600 font-light tracking-wide ml-0 sm:ml-16">
            Manage your accountant account information, security, and privacy preferences
          </p>
        </div>

        {}
        <div className="mb-4 sm:mb-6 border-b border-[var(--luxury-gold)]/20 overflow-x-auto bg-white/50 backdrop-blur-sm rounded-t-lg sm:rounded-t-xl px-4 sm:px-6">
          <div className="flex space-x-4 sm:space-x-8 min-w-max">
            <button
              onClick={() => setActiveTab('profile')}
              className={`py-3 sm:py-4 px-2 sm:px-1 border-b-2 font-semibold text-xs sm:text-sm transition-all duration-300 whitespace-nowrap ${
                activeTab === 'profile'
                  ? 'border-[var(--luxury-gold)] text-[var(--luxury-gold)] shadow-sm'
                  : 'border-transparent text-gray-500 hover:text-[var(--luxury-gold)] hover:border-[var(--luxury-gold)]/30'
              }`}
            >
              <User className={`w-4 h-4 sm:w-5 sm:h-5 inline mr-2 ${activeTab === 'profile' ? 'text-[var(--luxury-gold)]' : ''}`} />
              Profile Information
            </button>
            <button
              onClick={() => setActiveTab('password')}
              className={`py-3 sm:py-4 px-2 sm:px-1 border-b-2 font-semibold text-xs sm:text-sm transition-all duration-300 whitespace-nowrap ${
                activeTab === 'password'
                  ? 'border-[var(--luxury-gold)] text-[var(--luxury-gold)] shadow-sm'
                  : 'border-transparent text-gray-500 hover:text-[var(--luxury-gold)] hover:border-[var(--luxury-gold)]/30'
              }`}
            >
              <KeyRound className={`w-4 h-4 sm:w-5 sm:h-5 inline mr-2 ${activeTab === 'password' ? 'text-[var(--luxury-gold)]' : ''}`} />
              Change Password
            </button>
            <button
              onClick={() => setActiveTab('mfa')}
              className={`py-3 sm:py-4 px-2 sm:px-1 border-b-2 font-semibold text-xs sm:text-sm transition-all duration-300 whitespace-nowrap ${
                activeTab === 'mfa'
                  ? 'border-[var(--luxury-gold)] text-[var(--luxury-gold)] shadow-sm'
                  : 'border-transparent text-gray-500 hover:text-[var(--luxury-gold)] hover:border-[var(--luxury-gold)]/30'
              }`}
            >
              <Shield className={`w-4 h-4 sm:w-5 sm:h-5 inline mr-2 ${activeTab === 'mfa' ? 'text-[var(--luxury-gold)]' : ''}`} />
              Two-Factor Authentication
            </button>
            <button
              onClick={() => setActiveTab('sessions')}
              className={`py-3 sm:py-4 px-2 sm:px-1 border-b-2 font-semibold text-xs sm:text-sm transition-all duration-300 whitespace-nowrap ${
                activeTab === 'sessions'
                  ? 'border-[var(--luxury-gold)] text-[var(--luxury-gold)] shadow-sm'
                  : 'border-transparent text-gray-500 hover:text-[var(--luxury-gold)] hover:border-[var(--luxury-gold)]/30'
              }`}
            >
              <Monitor className={`w-4 h-4 sm:w-5 sm:h-5 inline mr-2 ${activeTab === 'sessions' ? 'text-[var(--luxury-gold)]' : ''}`} />
              Active Sessions
            </button>
            <button
              onClick={() => setActiveTab('gdpr')}
              className={`py-3 sm:py-4 px-2 sm:px-1 border-b-2 font-semibold text-xs sm:text-sm transition-all duration-300 whitespace-nowrap ${
                activeTab === 'gdpr'
                  ? 'border-[var(--luxury-gold)] text-[var(--luxury-gold)] shadow-sm'
                  : 'border-transparent text-gray-500 hover:text-[var(--luxury-gold)] hover:border-[var(--luxury-gold)]/30'
              }`}
            >
              <Database className={`w-4 h-4 sm:w-5 sm:h-5 inline mr-2 ${activeTab === 'gdpr' ? 'text-[var(--luxury-gold)]' : ''}`} />
              Data Privacy
            </button>
          </div>
        </div>

        {}
        {activeTab === 'profile' && (
          <div className="luxury-glass rounded-sm p-4 sm:p-6 lg:p-8 border border-[var(--luxury-gold)]/20 shadow-2xl animate-slide-up">
            <form onSubmit={handleSubmitProfile(onSubmitProfile)} className="space-y-5 sm:space-y-6">
              {}
              <div className="flex flex-col sm:flex-row items-center sm:items-start gap-4 sm:gap-6 pb-5 sm:pb-6 border-b border-gray-200">
                <div className="relative">
                  {(avatarPreview || userInfo?.avatar) && !avatarError ? (
                    <img
                      src={avatarPreview || normalizeImageUrl(userInfo?.avatar)}
                      alt="Profile"
                      className="w-20 h-20 sm:w-24 sm:h-24 rounded-full object-cover ring-4 ring-[var(--luxury-gold)]/20 shadow-lg"
                      onError={() => {
                        // If image fails to load, show default avatar
                        setAvatarError(true);
                      }}
                    />
                  ) : (
                    <div className="w-20 h-20 sm:w-24 sm:h-24 rounded-full bg-gradient-to-br from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] flex items-center justify-center ring-4 ring-[var(--luxury-gold)]/20 shadow-lg">
                      <User className="w-10 h-10 sm:w-12 sm:h-12 text-white" />
                    </div>
                  )}
                  <label
                    htmlFor="avatar-upload"
                    className="absolute bottom-0 right-0 p-2 bg-gradient-to-br from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] rounded-full cursor-pointer hover:from-[var(--luxury-gold-light)] hover:to-[var(--luxury-gold)] transition-all duration-300 shadow-lg hover:shadow-xl hover:shadow-[var(--luxury-gold)]/40 hover:-translate-y-0.5 active:translate-y-0"
                  >
                    <Camera className="w-3.5 h-3.5 sm:w-4 sm:h-4 text-white" />
                    <input
                      id="avatar-upload"
                      type="file"
                      accept="image/*"
                      onChange={handleAvatarChange}
                      className="hidden"
                    />
                  </label>
                </div>
              </div>

              <div>
                <label className="block text-sm sm:text-base font-medium text-gray-700 mb-2">
                  <User className="w-4 h-4 sm:w-5 sm:h-5 inline mr-2 text-[var(--luxury-gold)]" />
                  Full Name
                  <span className="text-red-500 ml-1">*</span>
                </label>
                <input
                  {...registerProfile('name')}
                  type="text"
                  className={`luxury-input text-sm sm:text-base ${
                    profileErrors.name ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''
                  }`}
                  placeholder="Enter your full name"
                />
                {profileErrors.name && (
                  <p className="mt-1.5 text-xs sm:text-sm text-red-600 font-light flex items-center gap-1.5">
                    <AlertCircle className="w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0" />
                    {profileErrors.name.message}
                  </p>
                )}
              </div>

              {}
              <div>
                <label className="block text-sm sm:text-base font-medium text-gray-700 mb-2">
                  <Mail className="w-4 h-4 sm:w-5 sm:h-5 inline mr-2 text-[var(--luxury-gold)]" />
                  Email Address
                  <span className="text-red-500 ml-1">*</span>
                </label>
                <input
                  {...registerProfile('email')}
                  type="email"
                  className={`luxury-input text-sm sm:text-base ${
                    profileErrors.email ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''
                  }`}
                  placeholder="Enter your email"
                />
                {profileErrors.email && (
                  <p className="mt-1.5 text-xs sm:text-sm text-red-600 font-light flex items-center gap-1.5">
                    <AlertCircle className="w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0" />
                    {profileErrors.email.message}
                  </p>
                )}
              </div>

              {}
              <div>
                <label className="block text-sm sm:text-base font-medium text-gray-700 mb-2">
                  <Phone className="w-4 h-4 sm:w-5 sm:h-5 inline mr-2 text-[var(--luxury-gold)]" />
                  Phone Number
                  <span className="text-red-500 ml-1">*</span>
                </label>
                <input
                  {...registerProfile('phone')}
                  type="tel"
                  className={`luxury-input text-sm sm:text-base ${
                    profileErrors.phone ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''
                  }`}
                  placeholder="Enter your phone number"
                />
                {profileErrors.phone && (
                  <p className="mt-1.5 text-xs sm:text-sm text-red-600 font-light flex items-center gap-1.5">
                    <AlertCircle className="w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0" />
                    {profileErrors.phone.message}
                  </p>
                )}
              </div>

              {}
              <div className="flex justify-end pt-4 sm:pt-5 border-t border-gray-200">
                <button
                  type="submit"
                  className="btn-luxury-primary flex items-center space-x-2 px-4 sm:px-6 py-2.5 sm:py-3 rounded-sm font-semibold text-xs sm:text-sm relative"
                >
                  <span className="absolute inset-0 bg-gradient-to-r from-white/0 via-white/20 to-white/0 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-700"></span>
                  <Save className="w-4 h-4 sm:w-5 sm:h-5 relative z-10" />
                  <span className="relative z-10">Save Changes</span>
                </button>
              </div>
            </form>
          </div>
        )}

        {}
        {activeTab === 'password' && (
          <div className="luxury-glass rounded-sm p-4 sm:p-6 lg:p-8 border border-[var(--luxury-gold)]/20 shadow-2xl animate-slide-up">
            <form onSubmit={handleSubmitPassword(onSubmitPassword)} className="space-y-5 sm:space-y-6">
              {}
              <div className="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200/60 rounded-sm p-4 sm:p-5">
                <div className="flex items-start gap-3">
                  <div className="p-1.5 sm:p-2 bg-blue-100 rounded-full flex-shrink-0">
                    <KeyRound className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600" />
                  </div>
                  <div>
                    <h4 className="text-sm sm:text-base font-semibold text-blue-900 mb-1.5">
                      Password Requirements
                    </h4>
                    <ul className="text-xs sm:text-sm text-blue-700 space-y-1 font-light">
                      <li className="flex items-start gap-2">
                        <span className="text-blue-500 mt-0.5">•</span>
                        <span>At least 6 characters long</span>
                      </li>
                      <li className="flex items-start gap-2">
                        <span className="text-blue-500 mt-0.5">•</span>
                        <span>Use a combination of letters and numbers for better security</span>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>

              {}
              <div>
                <label className="block text-sm sm:text-base font-medium text-gray-700 mb-2">
                  <Lock className="w-4 h-4 sm:w-5 sm:h-5 inline mr-2 text-[var(--luxury-gold)]" />
                  Current Password
                  <span className="text-red-500 ml-1">*</span>
                </label>
                <div className="relative">
                  <input
                    {...registerPassword('currentPassword')}
                    type={showPassword.current ? 'text' : 'password'}
                    className={`luxury-input text-sm sm:text-base pr-10 sm:pr-12 ${
                      passwordErrors.currentPassword ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''
                    }`}
                    placeholder="Enter your current password"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword({ ...showPassword, current: !showPassword.current })}
                    className="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-[var(--luxury-gold)] transition-colors"
                  >
                    {showPassword.current ? (
                      <EyeOff className="w-4 h-4 sm:w-5 sm:h-5" />
                    ) : (
                      <Eye className="w-4 h-4 sm:w-5 sm:h-5" />
                    )}
                  </button>
                </div>
                {passwordErrors.currentPassword && (
                  <p className="mt-1.5 text-xs sm:text-sm text-red-600 font-light flex items-center gap-1.5">
                    <AlertCircle className="w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0" />
                    {passwordErrors.currentPassword.message}
                  </p>
                )}
              </div>

              {}
              <div>
                <label className="block text-sm sm:text-base font-medium text-gray-700 mb-2">
                  <Lock className="w-4 h-4 sm:w-5 sm:h-5 inline mr-2 text-[var(--luxury-gold)]" />
                  New Password
                  <span className="text-red-500 ml-1">*</span>
                </label>
                <div className="relative">
                  <input
                    {...registerPassword('newPassword')}
                    type={showPassword.new ? 'text' : 'password'}
                    className={`luxury-input text-sm sm:text-base pr-10 sm:pr-12 ${
                      passwordErrors.newPassword ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''
                    }`}
                    placeholder="Enter your new password"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword({ ...showPassword, new: !showPassword.new })}
                    className="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-[var(--luxury-gold)] transition-colors"
                  >
                    {showPassword.new ? (
                      <EyeOff className="w-4 h-4 sm:w-5 sm:h-5" />
                    ) : (
                      <Eye className="w-4 h-4 sm:w-5 sm:h-5" />
                    )}
                  </button>
                </div>
                {passwordErrors.newPassword && (
                  <p className="mt-1.5 text-xs sm:text-sm text-red-600 font-light flex items-center gap-1.5">
                    <AlertCircle className="w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0" />
                    {passwordErrors.newPassword.message}
                  </p>
                )}
              </div>

              {}
              <div>
                <label className="block text-sm sm:text-base font-medium text-gray-700 mb-2">
                  <Lock className="w-4 h-4 sm:w-5 sm:h-5 inline mr-2 text-[var(--luxury-gold)]" />
                  Confirm New Password
                  <span className="text-red-500 ml-1">*</span>
                </label>
                <div className="relative">
                  <input
                    {...registerPassword('confirmPassword')}
                    type={showPassword.confirm ? 'text' : 'password'}
                    className={`luxury-input text-sm sm:text-base pr-10 sm:pr-12 ${
                      passwordErrors.confirmPassword ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''
                    }`}
                    placeholder="Confirm your new password"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword({ ...showPassword, confirm: !showPassword.confirm })}
                    className="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-[var(--luxury-gold)] transition-colors"
                  >
                    {showPassword.confirm ? (
                      <EyeOff className="w-4 h-4 sm:w-5 sm:h-5" />
                    ) : (
                      <Eye className="w-4 h-4 sm:w-5 sm:h-5" />
                    )}
                  </button>
                </div>
                {passwordErrors.confirmPassword && (
                  <p className="mt-1.5 text-xs sm:text-sm text-red-600 font-light flex items-center gap-1.5">
                    <AlertCircle className="w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0" />
                    {passwordErrors.confirmPassword.message}
                  </p>
                )}
              </div>

              {}
              <div className="flex justify-end pt-4 sm:pt-5 border-t border-gray-200">
                <button
                  type="submit"
                  className="btn-luxury-primary flex items-center space-x-2 px-4 sm:px-6 py-2.5 sm:py-3 rounded-sm font-semibold text-xs sm:text-sm relative"
                >
                  <span className="absolute inset-0 bg-gradient-to-r from-white/0 via-white/20 to-white/0 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-700"></span>
                  <Lock className="w-4 h-4 sm:w-5 sm:h-5 relative z-10" />
                  <span className="relative z-10">Change Password</span>
                </button>
              </div>
            </form>
          </div>
        )}

        {}
        {activeTab === 'mfa' && (
          <div className="luxury-glass rounded-sm p-4 sm:p-6 lg:p-8 border border-[var(--luxury-gold)]/20 shadow-2xl animate-slide-up space-y-5 sm:space-y-6">
            {}
            <div>
              <h2 className="text-xl sm:text-2xl font-serif font-semibold text-gray-900 mb-2 flex items-center gap-2">
                <Shield className="w-5 h-5 sm:w-6 sm:h-6 text-[var(--luxury-gold)]" />
                Two-Factor Authentication
              </h2>
              <p className="text-xs sm:text-sm text-gray-600 font-light leading-relaxed">
                Add an extra layer of security to your account by requiring a verification code in addition to your password.
              </p>
            </div>

            {mfaStatus?.mfa_enabled ? (
              
              <div className="space-y-5 sm:space-y-6">
                {}
                <div className="bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200/60 rounded-sm p-4 sm:p-5 shadow-lg">
                  <div className="flex items-start sm:items-center gap-3 sm:gap-4">
                    <div className="p-2 sm:p-2.5 bg-green-100 rounded-full flex-shrink-0">
                      <ShieldCheck className="w-5 h-5 sm:w-6 sm:h-6 text-green-600" />
                    </div>
                    <div className="flex-1">
                      <h3 className="text-base sm:text-lg font-semibold text-green-900 mb-1">MFA is Enabled</h3>
                      <p className="text-xs sm:text-sm text-green-700 font-light mb-1.5">
                        Your account is protected with two-factor authentication.
                      </p>
                      <p className="text-xs text-green-600 font-medium">
                        Remaining backup codes: <span className="font-semibold">{mfaStatus.backup_codes_count}</span>
                      </p>
                    </div>
                  </div>
                </div>

                {}
                {showBackupCodes && (
                  <div className="bg-gradient-to-r from-yellow-50 to-amber-50 border border-yellow-200/60 rounded-sm p-4 sm:p-5 shadow-lg">
                    <div className="mb-4">
                      <h3 className="font-semibold text-yellow-900 mb-2 flex items-center gap-2 text-sm sm:text-base">
                        <AlertCircle className="w-5 h-5 text-yellow-600" />
                        Save Your Backup Codes
                      </h3>
                      <p className="text-xs sm:text-sm text-yellow-700 font-light leading-relaxed">
                        Store these codes in a safe place. Each code can only be used once.
                      </p>
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 sm:gap-3 mb-4">
                      {showBackupCodes.map((code, index) => (
                        <div
                          key={index}
                          className="bg-white border border-yellow-300/60 rounded-sm px-3 sm:px-4 py-2 sm:py-2.5 font-mono text-xs sm:text-sm flex items-center justify-between shadow-sm hover:shadow-md transition-shadow"
                        >
                          <span className="text-gray-900 font-medium">{code}</span>
                          <button
                            onClick={() => {
                              navigator.clipboard.writeText(code);
                              toast.success('Code copied!');
                            }}
                            className="text-yellow-600 hover:text-yellow-800 transition-colors p-1 hover:bg-yellow-50 rounded"
                          >
                            <Copy className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
                          </button>
                        </div>
                      ))}
                    </div>
                    <button
                      onClick={() => setShowBackupCodes(null)}
                      className="text-xs sm:text-sm text-yellow-700 hover:text-yellow-900 underline font-medium transition-colors"
                    >
                      I've saved these codes
                    </button>
                  </div>
                )}

                {}
                <div className="bg-white border border-gray-200 rounded-sm p-4 sm:p-5">
                  <h3 className="text-sm sm:text-base font-semibold text-gray-900 mb-2 flex items-center gap-2">
                    <RefreshCw className="w-4 h-4 sm:w-5 sm:h-5 text-[var(--luxury-gold)]" />
                    Backup Codes
                  </h3>
                  <p className="text-xs sm:text-sm text-gray-600 font-light mb-4 leading-relaxed">
                    If you lose access to your authenticator app, you can use backup codes to access your account.
                  </p>
                  <button
                    onClick={async () => {
                      try {
                        setLoading(true, 'Regenerating backup codes...');
                        const response = await authService.regenerateBackupCodes();
                        if (response.status === 'success' && response.data?.backup_codes) {
                          setShowBackupCodes(response.data.backup_codes);
                          await fetchMFAStatus();
                          toast.success('Backup codes regenerated. Please save them!');
                        }
                      } catch (error: unknown) {
                        toast.error(getUserFriendlyError(error) || 'Failed to regenerate backup codes');
                      } finally {
                        setLoading(false);
                      }
                    }}
                    className="flex items-center gap-2 px-4 sm:px-5 py-2.5 sm:py-3 bg-gradient-to-r from-yellow-50 to-amber-50 border border-yellow-200/60 rounded-sm text-sm sm:text-base font-medium text-yellow-900 hover:from-yellow-100 hover:to-amber-100 transition-all duration-300 shadow-sm hover:shadow-md hover:-translate-y-0.5 active:translate-y-0"
                  >
                    <RefreshCw className="w-4 h-4 sm:w-5 sm:h-5" />
                    Regenerate Backup Codes
                  </button>
                </div>

                {}
                <div className="border-t border-gray-200 pt-5 sm:pt-6">
                  <h3 className="text-sm sm:text-base font-semibold text-red-900 mb-2 flex items-center gap-2">
                    <ShieldOff className="w-4 h-4 sm:w-5 sm:h-5 text-red-600" />
                    Disable MFA
                  </h3>
                  <p className="text-xs sm:text-sm text-gray-600 font-light mb-4 leading-relaxed">
                    Disabling MFA will reduce the security of your account. We recommend keeping it enabled.
                  </p>
                  <button
                    onClick={async () => {
                      if (!window.confirm('Are you sure you want to disable MFA? This will reduce your account security.')) {
                        return;
                      }
                      try {
                        setLoading(true, 'Disabling MFA...');
                        const response = await authService.disableMFA();
                        if (response.status === 'success') {
                          await fetchMFAStatus();
                          toast.success('MFA disabled successfully');
                        }
                      } catch (error: unknown) {
                        toast.error(getUserFriendlyError(error) || 'Failed to disable MFA');
                      } finally {
                        setLoading(false);
                      }
                    }}
                    className="flex items-center gap-2 px-4 sm:px-5 py-2.5 sm:py-3 bg-gradient-to-r from-red-50 to-rose-50 border border-red-200/60 rounded-sm text-sm sm:text-base font-medium text-red-900 hover:from-red-100 hover:to-rose-100 transition-all duration-300 shadow-sm hover:shadow-md hover:-translate-y-0.5 active:translate-y-0"
                  >
                    <ShieldOff className="w-4 h-4 sm:w-5 sm:h-5" />
                    Disable MFA
                  </button>
                </div>
              </div>
            ) : (
              
              <div className="space-y-5 sm:space-y-6">
                {!mfaSecret ? (
                  
                  <div>
                    <button
                      onClick={async () => {
                        try {
                          setLoading(true, 'Initializing MFA...');
                          const response = await authService.initMFA();
                          if (response.status === 'success' && response.data) {
                            setMfaSecret(response.data.secret || '');
                            setMfaQrCode(response.data.qr_code || '');
                          }
                        } catch (error: unknown) {
                          toast.error(getUserFriendlyError(error) || 'Failed to initialize MFA');
                        } finally {
                          setLoading(false);
                        }
                      }}
                      className="btn-luxury-primary w-full sm:w-auto flex items-center justify-center gap-2 px-6 sm:px-8 py-3 sm:py-3.5 rounded-sm font-semibold text-sm sm:text-base relative"
                    >
                      <span className="absolute inset-0 bg-gradient-to-r from-white/0 via-white/20 to-white/0 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-700"></span>
                      <Shield className="w-5 h-5 sm:w-6 sm:h-6 relative z-10" />
                      <span className="relative z-10">Enable Two-Factor Authentication</span>
                    </button>
                  </div>
                ) : (
                  
                  <div className="space-y-5 sm:space-y-6">
                    {}
                    <div className="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200/60 rounded-sm p-4 sm:p-5 shadow-lg">
                      <h3 className="font-semibold text-blue-900 mb-2 text-sm sm:text-base flex items-center gap-2">
                        <CheckCircle className="w-4 h-4 sm:w-5 sm:h-5" />
                        Step 1: Scan QR Code
                      </h3>
                      <p className="text-xs sm:text-sm text-blue-700 font-light mb-4 leading-relaxed">
                        Use your authenticator app (Google Authenticator, Authy, etc.) to scan this QR code.
                      </p>
                      {mfaQrCode && (
                        <div className="flex justify-center mb-4">
                          <img
                            src={mfaQrCode}
                            alt="MFA QR Code"
                            className="border-4 border-white rounded-lg shadow-xl max-w-[200px] sm:max-w-[250px]"
                          />
                        </div>
                      )}
                      <div className="bg-white border border-blue-200/60 rounded-sm p-3 sm:p-4 shadow-sm">
                        <div className="flex items-center justify-between mb-2">
                          <span className="text-xs sm:text-sm font-medium text-gray-700">Manual Entry Key:</span>
                          <button
                            onClick={() => setShowMfaSecret(!showMfaSecret)}
                            className="text-blue-600 hover:text-blue-800 transition-colors p-1 hover:bg-blue-50 rounded"
                          >
                            {showMfaSecret ? (
                              <EyeOff className="w-4 h-4 sm:w-5 sm:h-5" />
                            ) : (
                              <Eye className="w-4 h-4 sm:w-5 sm:h-5" />
                            )}
                          </button>
                        </div>
                        <div className="flex items-center gap-2">
                          <code className="flex-1 font-mono text-xs sm:text-sm bg-gray-50 p-2 sm:p-2.5 rounded border border-gray-200 text-gray-900 break-all">
                            {showMfaSecret ? mfaSecret : '••••••••••••••••'}
                          </code>
                          <button
                            onClick={() => {
                              navigator.clipboard.writeText(mfaSecret || '');
                              toast.success('Secret key copied!');
                            }}
                            className="px-3 sm:px-4 py-2 bg-gradient-to-r from-blue-100 to-indigo-100 text-blue-700 rounded-sm hover:from-blue-200 hover:to-indigo-200 transition-all duration-300 shadow-sm hover:shadow-md hover:-translate-y-0.5 active:translate-y-0"
                          >
                            <Copy className="w-4 h-4 sm:w-5 sm:h-5" />
                          </button>
                        </div>
                      </div>
                    </div>

                    {}
                    <div className="bg-white border border-gray-200 rounded-sm p-4 sm:p-5">
                      <h3 className="font-semibold text-gray-900 mb-2 text-sm sm:text-base flex items-center gap-2">
                        <KeyRound className="w-4 h-4 sm:w-5 sm:h-5 text-[var(--luxury-gold)]" />
                        Step 2: Verify Setup
                      </h3>
                      <p className="text-xs sm:text-sm text-gray-600 font-light mb-4 leading-relaxed">
                        Enter the 6-digit code from your authenticator app to complete the setup.
                      </p>
                      <div className="space-y-4">
                        <div>
                          <label className="block text-sm sm:text-base font-medium text-gray-700 mb-2">
                            Verification Code
                          </label>
                          <input
                            type="text"
                            value={mfaVerificationToken}
                            onChange={(e) => setMfaVerificationToken(e.target.value.replace(/\D/g, '').slice(0, 6))}
                            placeholder="000000"
                            maxLength={6}
                            className="luxury-input text-center text-lg sm:text-xl tracking-widest font-mono"
                          />
                        </div>
                        <div className="flex flex-col sm:flex-row gap-3">
                          <button
                            onClick={async () => {
                              if (!mfaVerificationToken || mfaVerificationToken.length !== 6) {
                                toast.error('Please enter a valid 6-digit code');
                                return;
                              }
                              try {
                                setLoading(true, 'Enabling MFA...');
                                const response = await authService.enableMFA(mfaSecret || '', mfaVerificationToken);
                                if (response.status === 'success' && response.data?.backup_codes) {
                                  setShowBackupCodes(response.data.backup_codes);
                                  await fetchMFAStatus();
                                  setMfaSecret(null);
                                  setMfaQrCode(null);
                                  setMfaVerificationToken('');
                                  toast.success('MFA enabled successfully!');
                                }
                              } catch (error: unknown) {
                                toast.error(getUserFriendlyError(error) || 'Invalid verification code');
                              } finally {
                                setLoading(false);
                              }
                            }}
                            className="btn-luxury-primary flex-1 flex items-center justify-center gap-2 px-4 sm:px-6 py-2.5 sm:py-3 rounded-sm font-semibold text-sm sm:text-base relative"
                          >
                            <span className="absolute inset-0 bg-gradient-to-r from-white/0 via-white/20 to-white/0 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-700"></span>
                            <ShieldCheck className="w-4 h-4 sm:w-5 sm:h-5 relative z-10" />
                            <span className="relative z-10">Verify & Enable</span>
                          </button>
                          <button
                            onClick={() => {
                              setMfaSecret(null);
                              setMfaQrCode(null);
                              setMfaVerificationToken('');
                              setShowMfaSecret(false);
                            }}
                            className="px-4 sm:px-6 py-2.5 sm:py-3 border border-gray-300 text-gray-700 rounded-sm hover:bg-gray-50 transition-all duration-300 font-medium text-sm sm:text-base shadow-sm hover:shadow-md hover:-translate-y-0.5 active:translate-y-0"
                          >
                            Cancel
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        )}

        {/* Sessions Tab */}
        {activeTab === 'sessions' && (
          <SessionsTab />
        )}

        {/* GDPR Tab */}
        {activeTab === 'gdpr' && (
          <GDPRTab />
        )}
      </div>
    </div>
  );
};

const SessionsTab: React.FC = () => {
  const [sessions, setSessions] = useState<UserSession[]>([]);
  const [loading, setLoading] = useState(true);
  const abortControllerRef = useRef<AbortController | null>(null);

  useEffect(() => {
    // Cancel previous request if exists
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }

    // Create new abort controller
    abortControllerRef.current = new AbortController();

    fetchSessions();

    // Cleanup: abort request on unmount
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, []);

  const fetchSessions = async () => {
    try {
      setLoading(true);
      const response = await sessionService.getMySessions();
      setSessions(response.data?.sessions || []);
    } catch (error: unknown) {
      const isAbortError = (e: unknown): boolean => {
        if (typeof e === 'object' && e !== null) {
          const err = e as { name?: string; code?: string };
          return err.name === 'AbortError' || err.code === 'ERR_CANCELED';
        }
        return false;
      };
      if (isAbortError(error)) {
        return;
      }
      toast.error(getUserFriendlyError(error) || 'Unable to load sessions');
    } finally {
      setLoading(false);
    }
  };

  const getDeviceIcon = (userAgent?: string) => {
    if (!userAgent) return <Monitor className="w-5 h-5 text-[var(--luxury-gold)]" />;
    if (userAgent.includes('Mobile')) return <Smartphone className="w-5 h-5 text-blue-500" />;
    if (userAgent.includes('Tablet')) return <Tablet className="w-5 h-5 text-purple-500" />;
    return <Monitor className="w-5 h-5 text-[var(--luxury-gold)]" />;
  };

  const getDeviceName = (userAgent?: string) => {
    if (!userAgent) return 'Unknown Device';
    if (userAgent.includes('Chrome')) return 'Chrome Browser';
    if (userAgent.includes('Firefox')) return 'Firefox Browser';
    if (userAgent.includes('Safari')) return 'Safari Browser';
    if (userAgent.includes('Edge')) return 'Edge Browser';
    if (userAgent.includes('Mobile')) return 'Mobile Device';
    if (userAgent.includes('Tablet')) return 'Tablet Device';
    return 'Web Browser';
  };

  const handleRevoke = async (sessionId: number) => {
    if (!confirm('Are you sure you want to revoke this session?')) return;

    try {
      const response = await sessionService.revokeSession(sessionId);
      if (response.data?.logout_required) {
        toast.warning('Your current session has been revoked. You will be logged out.');
        setTimeout(() => {
          window.location.href = '/';
        }, 2000);
      } else {
        toast.success('Session revoked successfully');
        fetchSessions();
      }
    } catch (error: unknown) {
      if (getUserFriendlyError(error) === 401) {
        toast.warning('Your session has been revoked. You will be logged out.');
        setTimeout(() => {
          window.location.href = '/';
        }, 2000);
      } else {
        toast.error(getUserFriendlyError(error) || 'Unable to revoke session');
      }
    }
  };

  const handleRevokeAll = async () => {
    if (!confirm('Are you sure you want to revoke all other sessions? This will also log you out.')) return;

    try {
      const response = await sessionService.revokeAllSessions();
      if (response.data?.logout_required) {
        toast.warning(response.message || 'All sessions have been revoked. You will be logged out.');
        setTimeout(() => {
          window.location.href = '/';
        }, 2000);
      } else {
        toast.success(response.message || 'All sessions revoked');
        fetchSessions();
      }
    } catch (error: unknown) {
      if (getUserFriendlyError(error) === 401) {
        toast.warning('All sessions have been revoked. You will be logged out.');
        setTimeout(() => {
          window.location.href = '/';
        }, 2000);
      } else {
        toast.error(getUserFriendlyError(error) || 'Unable to revoke sessions');
      }
    }
  };

  if (loading) {
    return (
      <div className="luxury-glass rounded-sm p-4 sm:p-6 lg:p-8 border border-[var(--luxury-gold)]/20 shadow-2xl">
        <Loading text="Loading sessions..." />
      </div>
    );
  }

  return (
    <div className="luxury-glass rounded-sm p-4 sm:p-6 lg:p-8 border border-[var(--luxury-gold)]/20 shadow-2xl animate-slide-up space-y-5 sm:space-y-6">
      <div>
        <h2 className="text-xl sm:text-2xl font-serif font-semibold text-gray-900 mb-2 flex items-center gap-2">
          <Monitor className="w-5 h-5 sm:w-6 sm:h-6 text-[var(--luxury-gold)]" />
          Active Sessions
        </h2>
        <p className="text-xs sm:text-sm text-gray-600 font-light">
          Manage your active sessions across different devices
        </p>
      </div>

      {sessions.length === 0 ? (
        <div className="text-center py-12">
          <Monitor className="w-12 h-12 mx-auto text-gray-400 mb-3" />
          <p className="text-gray-500 text-sm font-light">No active sessions</p>
        </div>
      ) : (
        <div className="space-y-4">
          {sessions.length > 1 && (
            <div className="flex justify-end pb-2">
              <button
                onClick={handleRevokeAll}
                className="px-4 sm:px-6 py-2 sm:py-2.5 bg-gradient-to-r from-red-600 to-red-700 text-white rounded-sm font-semibold hover:from-red-700 hover:to-red-800 shadow-lg hover:shadow-xl transition-all duration-200 text-xs sm:text-sm flex items-center gap-2"
              >
                <LogOut className="w-4 h-4" />
                Revoke All Other Sessions
              </button>
            </div>
          )}
          {sessions.map((session) => (
            <div
              key={session.id}
              className="bg-gradient-to-r from-slate-50 to-white border border-[var(--luxury-gold)]/20 rounded-sm p-4 sm:p-5 hover:shadow-lg hover:border-[var(--luxury-gold)]/40 transition-all duration-300"
            >
              <div className="flex items-start justify-between gap-4">
                <div className="flex items-start gap-4 flex-1">
                  <div className="p-2 sm:p-3 bg-gradient-to-br from-[var(--luxury-gold)]/10 to-[var(--luxury-gold-dark)]/10 rounded-sm flex-shrink-0">
                    {getDeviceIcon(session.user_agent)}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="font-semibold text-sm sm:text-base text-gray-900 mb-2">
                      {getDeviceName(session.user_agent)}
                    </p>
                    <p className="text-gray-600 text-xs sm:text-sm mb-1">
                      IP Address: <span className="font-mono">{session.ip_address || 'Unknown'}</span>
                    </p>
                    <p className="text-gray-500 text-xs mb-1">
                      Last Activity: {formatDate(session.last_activity)}
                    </p>
                    <p className="text-gray-500 text-xs">
                      Expires: {formatDate(session.expires_at)}
                    </p>
                  </div>
                </div>
                <button
                  onClick={() => handleRevoke(session.id)}
                  className="px-4 sm:px-5 py-2 sm:py-2.5 bg-gradient-to-r from-red-600 to-red-700 text-white rounded-sm hover:from-red-700 hover:to-red-800 shadow-md hover:shadow-lg transition-all duration-200 flex items-center gap-2 text-xs sm:text-sm font-semibold flex-shrink-0"
                >
                  <LogOut className="w-4 h-4" />
                  Revoke
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

const GDPRTab: React.FC = () => {
  const [requests, setRequests] = useState<GDPRRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [requesting, setRequesting] = useState(false);
  const abortControllerRef = useRef<AbortController | null>(null);

  useEffect(() => {
    // Cancel previous request if exists
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }

    // Create new abort controller
    abortControllerRef.current = new AbortController();

    fetchRequests();

    // Cleanup: abort request on unmount
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, []);

  const fetchRequests = async () => {
    try {
      setLoading(true);
      const response = await gdprService.getMyRequests();
      setRequests(response.data?.requests || []);
    } catch (error: unknown) {
      const isAbortError = (e: unknown): boolean => {
        if (typeof e === 'object' && e !== null) {
          const err = e as { name?: string; code?: string };
          return err.name === 'AbortError' || err.code === 'ERR_CANCELED';
        }
        return false;
      };
      if (isAbortError(error)) {
        return;
      }
      toast.error(getUserFriendlyError(error) || 'Unable to load GDPR requests');
    } finally {
      setLoading(false);
    }
  };

  const handleRequestExport = async () => {
    if (!confirm('Request a copy of your personal data? You will receive an email when ready.')) return;

    try {
      setRequesting(true);
      await gdprService.requestDataExport();
      toast.success('Data export request created. You will receive an email when ready.');
      fetchRequests();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to create export request');
    } finally {
      setRequesting(false);
    }
  };

  const handleRequestDeletion = async () => {
    if (!confirm('WARNING: This will permanently delete your account and all associated data. This action cannot be undone. Are you absolutely sure?')) return;
    if (!confirm('This is your last chance. Are you 100% certain you want to delete all your data?')) return;

    try {
      setRequesting(true);
      await gdprService.requestDataDeletion();
      toast.success('Deletion request created. Please check your email to confirm.');
      fetchRequests();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to create deletion request');
    } finally {
      setRequesting(false);
    }
  };

  const handleDownload = async (request: GDPRRequest) => {
    if (!request.verification_token) {
      toast.error('Verification token not available');
      return;
    }

    try {
      const blob = await gdprService.downloadExport(request.id, request.verification_token);
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `user_data_export_${request.id}.json`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      toast.success('Export downloaded successfully');
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to download export');
    }
  };

  if (loading) {
    return (
      <div className="luxury-glass rounded-sm p-4 sm:p-6 lg:p-8 border border-[var(--luxury-gold)]/20 shadow-2xl">
        <Loading text="Loading privacy data..." />
      </div>
    );
  }

  return (
    <div className="luxury-glass rounded-sm p-4 sm:p-6 lg:p-8 border border-[var(--luxury-gold)]/20 shadow-2xl animate-slide-up space-y-5 sm:space-y-6">
      <div>
        <h2 className="text-xl sm:text-2xl font-serif font-semibold text-gray-900 mb-2 flex items-center gap-2">
          <Database className="w-5 h-5 sm:w-6 sm:h-6 text-[var(--luxury-gold)]" />
          Data Privacy & GDPR Rights
        </h2>
        <p className="text-xs sm:text-sm text-gray-600 font-light">
          Manage your personal data and exercise your privacy rights under GDPR
        </p>
      </div>

      {/* Data Export */}
      <div className="bg-gradient-to-r from-blue-50/50 to-indigo-50/50 border border-blue-200/60 rounded-sm p-4 sm:p-6 shadow-lg">
        <div className="flex flex-col sm:flex-row items-start gap-4 mb-4">
          <div className="p-3 bg-gradient-to-br from-blue-100 to-indigo-100 rounded-sm flex-shrink-0">
            <Download className="w-6 h-6 sm:w-7 sm:h-7 text-blue-600" />
          </div>
          <div className="flex-1 min-w-0">
            <h3 className="text-base sm:text-lg font-semibold text-gray-900 mb-2">Export Your Data</h3>
            <p className="text-xs sm:text-sm text-gray-600 font-light mb-4 leading-relaxed">
              Request a copy of all your personal data stored in our system. You will receive an email with a download link when your data is ready.
            </p>
            <button
              onClick={handleRequestExport}
              disabled={requesting}
              className="btn-luxury-primary flex items-center gap-2 px-6 py-3 rounded-sm font-semibold text-sm sm:text-base relative disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <span className="absolute inset-0 bg-gradient-to-r from-white/0 via-white/20 to-white/0 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-700"></span>
              <Download className="w-5 h-5 relative z-10" />
              <span className="relative z-10">{requesting ? 'Requesting...' : 'Request Data Export'}</span>
            </button>
          </div>
        </div>
      </div>

      {/* Data Deletion */}
      <div className="bg-gradient-to-r from-red-50/50 to-rose-50/50 border-2 border-red-200/60 rounded-sm p-4 sm:p-6 shadow-lg">
        <div className="flex flex-col sm:flex-row items-start gap-4 mb-4">
          <div className="p-3 bg-gradient-to-br from-red-100 to-rose-100 rounded-sm flex-shrink-0">
            <Trash2 className="w-6 h-6 sm:w-7 sm:h-7 text-red-600" />
          </div>
          <div className="flex-1 min-w-0">
            <h3 className="text-base sm:text-lg font-semibold text-red-900 mb-2">Delete Your Data</h3>
            <div className="bg-white/80 border-2 border-red-200 rounded-sm p-3 sm:p-4 mb-4">
              <div className="flex items-start gap-3">
                <AlertCircle className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="text-xs sm:text-sm text-red-800 font-semibold mb-1">Warning: This action cannot be undone</p>
                  <p className="text-xs sm:text-sm text-red-700 font-light leading-relaxed">
                    Requesting data deletion will permanently remove your account and all associated data including bookings, payments, and personal information. This action is irreversible.
                  </p>
                </div>
              </div>
            </div>
            <button
              onClick={handleRequestDeletion}
              disabled={requesting}
              className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-red-600 to-red-700 text-white rounded-sm font-semibold hover:from-red-700 hover:to-red-800 shadow-lg hover:shadow-xl transition-all duration-200 text-sm sm:text-base disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Trash2 className="w-5 h-5" />
              {requesting ? 'Requesting...' : 'Request Data Deletion'}
            </button>
          </div>
        </div>
      </div>

      {/* Request History */}
      {requests.length > 0 && (
        <div className="border-t border-gray-200 pt-5 sm:pt-6">
          <h3 className="text-base sm:text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
            <FileText className="w-5 h-5 text-[var(--luxury-gold)]" />
            Request History
          </h3>
          <div className="space-y-3 sm:space-y-4">
            {requests.map((request) => (
              <div
                key={request.id}
                className="bg-gradient-to-r from-slate-50 to-white border border-[var(--luxury-gold)]/20 rounded-sm p-4 sm:p-5 hover:shadow-md hover:border-[var(--luxury-gold)]/40 transition-all duration-300"
              >
                <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4">
                  <div className="flex-1 min-w-0">
                    <div className="flex flex-wrap items-center gap-3 mb-2">
                      {request.request_type === 'data_export' ? (
                        <Download className="w-5 h-5 text-blue-500 flex-shrink-0" />
                      ) : (
                        <Trash2 className="w-5 h-5 text-red-500 flex-shrink-0" />
                      )}
                      <h4 className="font-semibold text-sm sm:text-base text-gray-900">
                        {request.request_type === 'data_export' ? 'Data Export' : 'Data Deletion'}
                      </h4>
                      <span className={`px-3 py-1 rounded-full text-xs font-semibold border shadow-sm ${
                        request.status === 'completed' 
                          ? 'bg-gradient-to-r from-emerald-50 to-green-50 text-emerald-800 border-emerald-200' 
                          : request.status === 'pending' || request.status === 'processing'
                          ? 'bg-gradient-to-r from-amber-50 to-yellow-50 text-amber-800 border-amber-200'
                          : 'bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-200'
                      }`}>
                        {request.status.charAt(0).toUpperCase() + request.status.slice(1)}
                      </span>
                    </div>
                    <p className="text-xs sm:text-sm text-gray-600 font-light">
                      Created: {formatDate(request.created_at)}
                      {request.processed_at && ` • Processed: ${formatDate(request.processed_at)}`}
                    </p>
                  </div>
                  {request.request_type === 'data_export' && request.status === 'completed' && request.verification_token && (
                    <button
                      onClick={() => handleDownload(request)}
                      className="btn-luxury-primary flex items-center gap-2 px-4 sm:px-6 py-2 sm:py-2.5 rounded-sm font-semibold text-xs sm:text-sm relative flex-shrink-0"
                    >
                      <span className="absolute inset-0 bg-gradient-to-r from-white/0 via-white/20 to-white/0 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-700"></span>
                      <Download className="w-4 h-4 relative z-10" />
                      <span className="relative z-10">Download</span>
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default ProfilePage;
