import { useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useToast } from "@/hooks/use-toast";
import { apiRequest, queryClient } from "@/lib/queryClient";
import {
  User,
  Lock,
  Bell,
  Palette,
  CreditCard,
  Shield,
  Mail,
  Phone,
  Globe,
  Clock,
  Eye,
  EyeOff,
  Upload,
  Check,
  Loader2
} from "lucide-react";
import type { UserPreferences } from "@shared/schema";

export default function Settings() {
  const { user } = useAuth();
  const { toast } = useToast();
  const [showPassword, setShowPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);

  // Fetch user preferences
  const { data: preferences, isLoading: preferencesLoading } = useQuery<UserPreferences>({
    queryKey: ["/api/user/preferences"],
  });

  // Fetch user subscription
  const { data: subscription } = useQuery<any>({
    queryKey: ["/api/user/subscription"],
  });

  // Profile update mutation
  const profileMutation = useMutation({
    mutationFn: async (data: any) => {
      return apiRequest("/api/user/profile", "PUT", data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/auth/user"] });
      toast({
        title: "Profile updated",
        description: "Your profile has been updated successfully",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to update profile",
        variant: "destructive",
      });
    },
  });

  // Password change mutation
  const passwordMutation = useMutation({
    mutationFn: async (data: any) => {
      return apiRequest("/api/user/change-password", "POST", data);
    },
    onSuccess: () => {
      toast({
        title: "Password changed",
        description: "Your password has been changed successfully",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to change password",
        variant: "destructive",
      });
    },
  });

  // Preferences update mutation
  const preferencesMutation = useMutation({
    mutationFn: async (data: any) => {
      return apiRequest("/api/user/preferences", "PUT", data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/user/preferences"] });
      toast({
        title: "Preferences updated",
        description: "Your preferences have been saved",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to update preferences",
        variant: "destructive",
      });
    },
  });

  const handleProfileSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    profileMutation.mutate({
      firstName: formData.get("firstName"),
      lastName: formData.get("lastName"),
      email: formData.get("email"),
      phone: formData.get("phone"),
    });
  };

  const handlePasswordSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const currentPassword = formData.get("currentPassword");
    const newPassword = formData.get("newPassword");
    const confirmPassword = formData.get("confirmPassword");

    if (newPassword !== confirmPassword) {
      toast({
        title: "Error",
        description: "New passwords do not match",
        variant: "destructive",
      });
      return;
    }

    passwordMutation.mutate({ currentPassword, newPassword });
  };

  const handlePreferenceUpdate = (key: string, value: any) => {
    preferencesMutation.mutate({ [key]: value });
  };

  if (preferencesLoading) {
    return (
      <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div className="flex items-center justify-center min-h-[400px]">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-6">
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-gray-900">Settings</h1>
        <p className="text-gray-600 mt-2">Manage your account settings and preferences</p>
      </div>

      <Tabs defaultValue="profile" className="space-y-6">
        <TabsList className="grid w-full grid-cols-3 lg:grid-cols-6">
          <TabsTrigger value="profile" data-testid="tab-profile">
            <User className="h-4 w-4 mr-2" />
            <span className="hidden sm:inline">Profile</span>
          </TabsTrigger>
          <TabsTrigger value="password" data-testid="tab-password">
            <Lock className="h-4 w-4 mr-2" />
            <span className="hidden sm:inline">Password</span>
          </TabsTrigger>
          <TabsTrigger value="notifications" data-testid="tab-notifications">
            <Bell className="h-4 w-4 mr-2" />
            <span className="hidden sm:inline">Notifications</span>
          </TabsTrigger>
          <TabsTrigger value="theme" data-testid="tab-theme">
            <Palette className="h-4 w-4 mr-2" />
            <span className="hidden sm:inline">Theme</span>
          </TabsTrigger>
          <TabsTrigger value="subscription" data-testid="tab-subscription">
            <CreditCard className="h-4 w-4 mr-2" />
            <span className="hidden sm:inline">Subscription</span>
          </TabsTrigger>
          <TabsTrigger value="privacy" data-testid="tab-privacy">
            <Shield className="h-4 w-4 mr-2" />
            <span className="hidden sm:inline">Privacy</span>
          </TabsTrigger>
        </TabsList>

        {/* Profile Tab */}
        <TabsContent value="profile" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center">
                <User className="h-5 w-5 mr-2" />
                Profile Information
              </CardTitle>
              <CardDescription>Update your personal information and profile picture</CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Profile Picture */}
              <div className="flex items-center space-x-4">
                <Avatar className="h-20 w-20">
                  <AvatarImage src={(user as any)?.profileImageUrl} alt="Profile" />
                  <AvatarFallback className="bg-gradient-to-br from-blue-500 to-purple-600 text-white text-xl">
                    {((user as any)?.firstName?.[0] || '') + ((user as any)?.lastName?.[0] || '')}
                  </AvatarFallback>
                </Avatar>
                <div>
                  <Button variant="outline" size="sm" data-testid="button-upload-photo">
                    <Upload className="h-4 w-4 mr-2" />
                    Upload Photo
                  </Button>
                  <p className="text-sm text-gray-500 mt-1">JPG, PNG or GIF (MAX. 2MB)</p>
                </div>
              </div>

              <Separator />

              {/* Profile Form */}
              <form onSubmit={handleProfileSubmit} className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="firstName">First Name</Label>
                    <Input
                      id="firstName"
                      name="firstName"
                      defaultValue={(user as any)?.firstName}
                      data-testid="input-first-name"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="lastName">Last Name</Label>
                    <Input
                      id="lastName"
                      name="lastName"
                      defaultValue={(user as any)?.lastName}
                      data-testid="input-last-name"
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="email">Email</Label>
                  <Input
                    id="email"
                    name="email"
                    type="email"
                    defaultValue={(user as any)?.email}
                    data-testid="input-email"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="phone">Phone Number</Label>
                  <Input
                    id="phone"
                    name="phone"
                    type="tel"
                    placeholder="+1 (555) 000-0000"
                    data-testid="input-phone"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="sport">Primary Sport</Label>
                  <Input
                    id="sport"
                    name="sport"
                    defaultValue={(user as any)?.sport}
                    disabled
                    data-testid="input-sport"
                  />
                </div>

                <Button type="submit" disabled={profileMutation.isPending} data-testid="button-save-profile">
                  {profileMutation.isPending ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      Saving...
                    </>
                  ) : (
                    <>
                      <Check className="h-4 w-4 mr-2" />
                      Save Changes
                    </>
                  )}
                </Button>
              </form>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Password Tab */}
        <TabsContent value="password" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center">
                <Lock className="h-5 w-5 mr-2" />
                Change Password
              </CardTitle>
              <CardDescription>Update your password to keep your account secure</CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handlePasswordSubmit} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="currentPassword">Current Password</Label>
                  <div className="relative">
                    <Input
                      id="currentPassword"
                      name="currentPassword"
                      type={showPassword ? "text" : "password"}
                      data-testid="input-current-password"
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      className="absolute right-2 top-1/2 -translate-y-1/2"
                      onClick={() => setShowPassword(!showPassword)}
                    >
                      {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                    </Button>
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="newPassword">New Password</Label>
                  <div className="relative">
                    <Input
                      id="newPassword"
                      name="newPassword"
                      type={showNewPassword ? "text" : "password"}
                      data-testid="input-new-password"
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      className="absolute right-2 top-1/2 -translate-y-1/2"
                      onClick={() => setShowNewPassword(!showNewPassword)}
                    >
                      {showNewPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                    </Button>
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="confirmPassword">Confirm New Password</Label>
                  <Input
                    id="confirmPassword"
                    name="confirmPassword"
                    type="password"
                    data-testid="input-confirm-password"
                  />
                </div>

                <Button type="submit" disabled={passwordMutation.isPending} data-testid="button-change-password">
                  {passwordMutation.isPending ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      Changing...
                    </>
                  ) : (
                    <>
                      <Check className="h-4 w-4 mr-2" />
                      Change Password
                    </>
                  )}
                </Button>
              </form>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Notifications Tab */}
        <TabsContent value="notifications" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center">
                <Bell className="h-5 w-5 mr-2" />
                Notification Preferences
              </CardTitle>
              <CardDescription>Manage how you receive notifications</CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Notification Channels */}
              <div className="space-y-4">
                <h3 className="font-semibold">Notification Channels</h3>
                
                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label className="flex items-center">
                      <Mail className="h-4 w-4 mr-2" />
                      Email Notifications
                    </Label>
                    <p className="text-sm text-gray-500">Receive notifications via email</p>
                  </div>
                  <Switch
                    checked={preferences?.emailNotifications ?? true}
                    onCheckedChange={(checked) => handlePreferenceUpdate("emailNotifications", checked)}
                    data-testid="switch-email-notifications"
                  />
                </div>

                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label className="flex items-center">
                      <Phone className="h-4 w-4 mr-2" />
                      SMS Notifications
                    </Label>
                    <p className="text-sm text-gray-500">Receive notifications via SMS</p>
                  </div>
                  <Switch
                    checked={preferences?.smsNotifications ?? false}
                    onCheckedChange={(checked) => handlePreferenceUpdate("smsNotifications", checked)}
                    data-testid="switch-sms-notifications"
                  />
                </div>

                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label className="flex items-center">
                      <Bell className="h-4 w-4 mr-2" />
                      Push Notifications
                    </Label>
                    <p className="text-sm text-gray-500">Receive in-app push notifications</p>
                  </div>
                  <Switch
                    checked={preferences?.pushNotifications ?? true}
                    onCheckedChange={(checked) => handlePreferenceUpdate("pushNotifications", checked)}
                    data-testid="switch-push-notifications"
                  />
                </div>
              </div>

              <Separator />

              {/* Notification Types */}
              <div className="space-y-4">
                <h3 className="font-semibold">Notification Types</h3>
                
                <div className="flex items-center justify-between">
                  <Label>Team Updates</Label>
                  <Switch
                    checked={preferences?.notificationTypes?.teamUpdates ?? true}
                    onCheckedChange={(checked) => 
                      handlePreferenceUpdate("notificationTypes", { 
                        ...preferences?.notificationTypes, 
                        teamUpdates: checked 
                      })
                    }
                    data-testid="switch-team-updates"
                  />
                </div>

                <div className="flex items-center justify-between">
                  <Label>Player Updates</Label>
                  <Switch
                    checked={preferences?.notificationTypes?.playerUpdates ?? true}
                    onCheckedChange={(checked) => 
                      handlePreferenceUpdate("notificationTypes", { 
                        ...preferences?.notificationTypes, 
                        playerUpdates: checked 
                      })
                    }
                    data-testid="switch-player-updates"
                  />
                </div>

                <div className="flex items-center justify-between">
                  <Label>Match Reminders</Label>
                  <Switch
                    checked={preferences?.notificationTypes?.matchReminders ?? true}
                    onCheckedChange={(checked) => 
                      handlePreferenceUpdate("notificationTypes", { 
                        ...preferences?.notificationTypes, 
                        matchReminders: checked 
                      })
                    }
                    data-testid="switch-match-reminders"
                  />
                </div>

                <div className="flex items-center justify-between">
                  <Label>Payment Reminders</Label>
                  <Switch
                    checked={preferences?.notificationTypes?.paymentReminders ?? true}
                    onCheckedChange={(checked) => 
                      handlePreferenceUpdate("notificationTypes", { 
                        ...preferences?.notificationTypes, 
                        paymentReminders: checked 
                      })
                    }
                    data-testid="switch-payment-reminders"
                  />
                </div>

                <div className="flex items-center justify-between">
                  <Label>System Alerts</Label>
                  <Switch
                    checked={preferences?.notificationTypes?.systemAlerts ?? true}
                    onCheckedChange={(checked) => 
                      handlePreferenceUpdate("notificationTypes", { 
                        ...preferences?.notificationTypes, 
                        systemAlerts: checked 
                      })
                    }
                    data-testid="switch-system-alerts"
                  />
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Theme Tab */}
        <TabsContent value="theme" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center">
                <Palette className="h-5 w-5 mr-2" />
                Theme & Layout
              </CardTitle>
              <CardDescription>Customize your interface appearance</CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="theme">Theme</Label>
                  <Select
                    value={preferences?.theme ?? "light"}
                    onValueChange={(value) => handlePreferenceUpdate("theme", value)}
                  >
                    <SelectTrigger id="theme" data-testid="select-theme">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="light">Light</SelectItem>
                      <SelectItem value="dark">Dark</SelectItem>
                      <SelectItem value="auto">Auto (System)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label>Compact Mode</Label>
                    <p className="text-sm text-gray-500">Reduce spacing and padding</p>
                  </div>
                  <Switch
                    checked={preferences?.compactMode ?? false}
                    onCheckedChange={(checked) => handlePreferenceUpdate("compactMode", checked)}
                    data-testid="switch-compact-mode"
                  />
                </div>

                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label>Collapse Sidebar by Default</Label>
                    <p className="text-sm text-gray-500">Start with sidebar minimized</p>
                  </div>
                  <Switch
                    checked={preferences?.sidebarCollapsed ?? false}
                    onCheckedChange={(checked) => handlePreferenceUpdate("sidebarCollapsed", checked)}
                    data-testid="switch-sidebar-collapsed"
                  />
                </div>
              </div>

              <Separator />

              <div className="space-y-4">
                <h3 className="font-semibold">Regional Settings</h3>
                
                <div className="space-y-2">
                  <Label htmlFor="language">Language</Label>
                  <Select
                    value={preferences?.language ?? "en"}
                    onValueChange={(value) => handlePreferenceUpdate("language", value)}
                  >
                    <SelectTrigger id="language" data-testid="select-language">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="en">English</SelectItem>
                      <SelectItem value="es">Español</SelectItem>
                      <SelectItem value="fr">Français</SelectItem>
                      <SelectItem value="de">Deutsch</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="timezone">Timezone</Label>
                  <Select
                    value={preferences?.timezone ?? "UTC"}
                    onValueChange={(value) => handlePreferenceUpdate("timezone", value)}
                  >
                    <SelectTrigger id="timezone" data-testid="select-timezone">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="UTC">UTC</SelectItem>
                      <SelectItem value="America/New_York">Eastern Time</SelectItem>
                      <SelectItem value="America/Chicago">Central Time</SelectItem>
                      <SelectItem value="America/Denver">Mountain Time</SelectItem>
                      <SelectItem value="America/Los_Angeles">Pacific Time</SelectItem>
                      <SelectItem value="Europe/London">London</SelectItem>
                      <SelectItem value="Europe/Paris">Paris</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="dateFormat">Date Format</Label>
                    <Select
                      value={preferences?.dateFormat ?? "MM/DD/YYYY"}
                      onValueChange={(value) => handlePreferenceUpdate("dateFormat", value)}
                    >
                      <SelectTrigger id="dateFormat" data-testid="select-date-format">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="MM/DD/YYYY">MM/DD/YYYY</SelectItem>
                        <SelectItem value="DD/MM/YYYY">DD/MM/YYYY</SelectItem>
                        <SelectItem value="YYYY-MM-DD">YYYY-MM-DD</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="timeFormat">Time Format</Label>
                    <Select
                      value={preferences?.timeFormat ?? "12h"}
                      onValueChange={(value) => handlePreferenceUpdate("timeFormat", value)}
                    >
                      <SelectTrigger id="timeFormat" data-testid="select-time-format">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="12h">12-hour</SelectItem>
                        <SelectItem value="24h">24-hour</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Subscription Tab */}
        <TabsContent value="subscription" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center">
                <CreditCard className="h-5 w-5 mr-2" />
                Subscription Management
              </CardTitle>
              <CardDescription>Manage your subscription and billing</CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Current Plan */}
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div>
                    <h3 className="font-semibold">Current Plan</h3>
                    <p className="text-sm text-gray-500">Your active subscription</p>
                  </div>
                  <Badge variant="default" className="text-lg px-4 py-1">
                    {subscription?.tier || "Regular"}
                  </Badge>
                </div>

                {subscription?.stripeSubscriptionId ? (
                  <div className="bg-blue-50 p-4 rounded-lg">
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm font-medium">Status</span>
                      <Badge variant={subscription?.status === 'active' ? 'default' : 'secondary'}>
                        {subscription?.status}
                      </Badge>
                    </div>
                    {subscription?.subscriptionEndDate && (
                      <div className="flex items-center justify-between text-sm">
                        <span className="text-gray-600">Next billing date</span>
                        <span className="font-medium">
                          {new Date(subscription.subscriptionEndDate).toLocaleDateString()}
                        </span>
                      </div>
                    )}
                  </div>
                ) : (
                  <div className="bg-gray-50 p-4 rounded-lg text-center">
                    <p className="text-sm text-gray-600">No active subscription</p>
                    <Button className="mt-3" data-testid="button-upgrade-plan">
                      Upgrade Plan
                    </Button>
                  </div>
                )}
              </div>

              <Separator />

              {/* Billing Information */}
              <div className="space-y-4">
                <h3 className="font-semibold">Billing Information</h3>
                <div className="space-y-2">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">Payment Method</span>
                    <span className="font-medium">•••• •••• •••• 4242</span>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">Customer ID</span>
                    <span className="font-mono text-xs">{(user as any)?.stripeCustomerId || "N/A"}</span>
                  </div>
                </div>
                <Button variant="outline" data-testid="button-manage-billing">
                  Manage Billing
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Privacy Tab */}
        <TabsContent value="privacy" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center">
                <Shield className="h-5 w-5 mr-2" />
                Privacy & Security Settings
              </CardTitle>
              <CardDescription>Control your privacy and security preferences</CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Profile Visibility */}
              <div className="space-y-4">
                <h3 className="font-semibold">Profile Visibility</h3>
                
                <div className="space-y-2">
                  <Label htmlFor="profileVisibility">Who can see your profile?</Label>
                  <Select
                    value={preferences?.profileVisibility ?? "team"}
                    onValueChange={(value) => handlePreferenceUpdate("profileVisibility", value)}
                  >
                    <SelectTrigger id="profileVisibility" data-testid="select-profile-visibility">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="public">Public - Everyone</SelectItem>
                      <SelectItem value="team">Team - Team members only</SelectItem>
                      <SelectItem value="private">Private - Only me</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="flex items-center justify-between">
                  <Label>Show email address</Label>
                  <Switch
                    checked={preferences?.showEmail ?? false}
                    onCheckedChange={(checked) => handlePreferenceUpdate("showEmail", checked)}
                    data-testid="switch-show-email"
                  />
                </div>

                <div className="flex items-center justify-between">
                  <Label>Show phone number</Label>
                  <Switch
                    checked={preferences?.showPhone ?? false}
                    onCheckedChange={(checked) => handlePreferenceUpdate("showPhone", checked)}
                    data-testid="switch-show-phone"
                  />
                </div>
              </div>

              <Separator />

              {/* Security Settings */}
              <div className="space-y-4">
                <h3 className="font-semibold">Security</h3>
                
                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label>Two-Factor Authentication</Label>
                    <p className="text-sm text-gray-500">Add an extra layer of security</p>
                  </div>
                  <Switch
                    checked={preferences?.twoFactorEnabled ?? false}
                    onCheckedChange={(checked) => handlePreferenceUpdate("twoFactorEnabled", checked)}
                    data-testid="switch-two-factor"
                  />
                </div>

                <Button variant="outline" data-testid="button-view-activity">
                  <Clock className="h-4 w-4 mr-2" />
                  View Login Activity
                </Button>
              </div>

              <Separator />

              {/* Data Management */}
              <div className="space-y-4">
                <h3 className="font-semibold text-red-600">Data Management</h3>
                
                <Button variant="outline" data-testid="button-download-data">
                  <Globe className="h-4 w-4 mr-2" />
                  Download My Data
                </Button>

                <Button variant="destructive" data-testid="button-delete-account">
                  Delete My Account
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
