import { useState, useRef, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useAuth } from "@/hooks/useAuth";
import { useToast } from "@/hooks/use-toast";
import { useTheme } from "@/components/theme-provider";
import { useAccessibility } from "@/components/accessibility-provider";
import { apiRequest } from "@/lib/queryClient";
import { 
  Settings, 
  User, 
  Shield, 
  Bell, 
  Palette, 
  Database, 
  Download,
  Upload,
  Save,
  RefreshCw,
  Globe,
  Lock,
  Mail,
  Smartphone,
  Eye,
  Accessibility,
  Type,
  Volume2,
  Keyboard,
  Check,
  AlertCircle,
  Info,
  Zap,
  Moon,
  Sun,
  Monitor,
  ChevronRight
} from "lucide-react";

export default function SettingsPage() {
  const { user } = useAuth();
  const { toast } = useToast();
  const { theme, setTheme } = useTheme();
  const { settings: accessibilitySettings, updateSetting: updateAccessibilitySetting, resetSettings: resetAccessibilitySettings } = useAccessibility();
  const queryClient = useQueryClient();
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  // Profile form state
  const [firstName, setFirstName] = useState((user as any)?.firstName || "");
  const [lastName, setLastName] = useState((user as any)?.lastName || "");
  const [email, setEmail] = useState((user as any)?.email || "");
  
  // Other settings state
  const [emailNotifications, setEmailNotifications] = useState(true);
  const [pushNotifications, setPushNotifications] = useState(true);
  const [language, setLanguage] = useState("en");
  const [timezone, setTimezone] = useState("UTC");
  const [isExporting, setIsExporting] = useState(false);
  const [isImporting, setIsImporting] = useState(false);
  const [activeTab, setActiveTab] = useState("profile");

  // Update form state when user data changes
  useEffect(() => {
    if (user) {
      setFirstName((user as any)?.firstName || "");
      setLastName((user as any)?.lastName || "");
      setEmail((user as any)?.email || "");
    }
  }, [user]);

  // Profile update mutation
  const updateProfileMutation = useMutation({
    mutationFn: async (profileData: { firstName: string; lastName: string; email: string }) => {
      const response = await apiRequest("PUT", "/api/auth/user", profileData);
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/auth/user"] });
      toast({
        title: "Success",
        description: "Profile updated successfully",
      });
    },
    onError: (error: Error) => {
      toast({
        title: "Error",
        description: error.message || "Failed to update profile",
        variant: "destructive",
      });
    },
  });

  const handleSaveProfile = () => {
    updateProfileMutation.mutate({
      firstName,
      lastName,
      email,
    });
  };

  const handleExportData = async () => {
    setIsExporting(true);
    try {
      const response = await fetch("/api/data/export", {
        method: "GET",
        headers: {
          "Authorization": `Bearer ${localStorage.getItem("token")}`,
        },
      });

      if (!response.ok) {
        throw new Error("Failed to export data");
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `sports-data-export-${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);

      toast({
        title: "Export Successful",
        description: "Your data has been exported successfully",
      });
    } catch (error) {
      toast({
        title: "Export Failed",
        description: "Failed to export data. Please try again.",
        variant: "destructive",
      });
    } finally {
      setIsExporting(false);
    }
  };

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

    setIsImporting(true);
    try {
      const formData = new FormData();
      formData.append("importFile", file);

      const response = await fetch("/api/data/import", {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error("Failed to import data");
      }

      const result = await response.json();
      
      toast({
        title: "Import Successful",
        description: `Imported ${result.importedRecords} of ${result.totalRecords} records successfully`,
      });

      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    } catch (error) {
      toast({
        title: "Import Failed",
        description: "Failed to import data. Please check the file format and try again.",
        variant: "destructive",
      });
    } finally {
      setIsImporting(false);
    }
  };

  const getThemeIcon = () => {
    if (theme === 'light') return <Sun className="h-4 w-4" />;
    if (theme === 'dark') return <Moon className="h-4 w-4" />;
    return <Monitor className="h-4 w-4" />;
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-slate-50 dark:from-gray-900 dark:via-blue-900/10 dark:to-gray-900">
      <div className="container mx-auto p-4 sm:p-6 lg:p-8">
        {/* Modern Header */}
        <div className="mb-8" data-tour="settings-header">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-3 bg-gradient-to-br from-primary to-primary/80 rounded-xl shadow-lg">
              <Settings className="h-6 w-6 text-white" />
            </div>
            <div>
              <h1 className="text-3xl sm:text-4xl font-bold bg-gradient-to-r from-gray-900 to-gray-600 dark:from-white dark:to-gray-300 bg-clip-text text-transparent">
                Settings
              </h1>
              <p className="text-gray-600 dark:text-gray-400 mt-1">
                Manage your preferences and customize your experience
              </p>
            </div>
          </div>
        </div>

        {/* Tabs Navigation */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
          {/* Modern Tab List */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-2">
            <TabsList className="grid w-full grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2 bg-transparent">
              <TabsTrigger 
                value="profile" 
                className="data-[state=active]:bg-gradient-to-br data-[state=active]:from-primary data-[state=active]:to-primary/80 data-[state=active]:text-white transition-all"
                data-tour="settings-profile-tab"
              >
                <User className="h-4 w-4 mr-2" />
                <span className="hidden sm:inline">Profile</span>
              </TabsTrigger>
              <TabsTrigger 
                value="security"
                className="data-[state=active]:bg-gradient-to-br data-[state=active]:from-primary data-[state=active]:to-primary/80 data-[state=active]:text-white transition-all"
              >
                <Shield className="h-4 w-4 mr-2" />
                <span className="hidden sm:inline">Security</span>
              </TabsTrigger>
              <TabsTrigger 
                value="notifications"
                className="data-[state=active]:bg-gradient-to-br data-[state=active]:from-primary data-[state=active]:to-primary/80 data-[state=active]:text-white transition-all"
                data-tour="settings-notifications-tab"
              >
                <Bell className="h-4 w-4 mr-2" />
                <span className="hidden sm:inline">Notifications</span>
              </TabsTrigger>
              <TabsTrigger 
                value="appearance"
                className="data-[state=active]:bg-gradient-to-br data-[state=active]:from-primary data-[state=active]:to-primary/80 data-[state=active]:text-white transition-all"
                data-tour="settings-appearance-tab"
              >
                <Palette className="h-4 w-4 mr-2" />
                <span className="hidden sm:inline">Appearance</span>
              </TabsTrigger>
              <TabsTrigger 
                value="accessibility"
                className="data-[state=active]:bg-gradient-to-br data-[state=active]:from-primary data-[state=active]:to-primary/80 data-[state=active]:text-white transition-all"
              >
                <Accessibility className="h-4 w-4 mr-2" />
                <span className="hidden sm:inline">Accessibility</span>
              </TabsTrigger>
              <TabsTrigger 
                value="data"
                className="data-[state=active]:bg-gradient-to-br data-[state=active]:from-primary data-[state=active]:to-primary/80 data-[state=active]:text-white transition-all"
              >
                <Database className="h-4 w-4 mr-2" />
                <span className="hidden sm:inline">Data</span>
              </TabsTrigger>
            </TabsList>
          </div>

          {/* Profile Tab */}
          <TabsContent value="profile" className="space-y-6">
            <Card className="border-0 shadow-xl bg-white dark:bg-gray-800 overflow-hidden">
              <div className="h-2 bg-gradient-to-r from-blue-500 via-purple-500 to-pink-500" />
              <CardHeader className="space-y-1 pb-6">
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle className="text-2xl flex items-center gap-2">
                      <User className="h-5 w-5 text-primary" />
                      Profile Information
                    </CardTitle>
                    <CardDescription className="mt-2">
                      Update your personal details and contact information
                    </CardDescription>
                  </div>
                  <Badge variant="secondary" className="hidden sm:flex">
                    <Check className="h-3 w-3 mr-1" />
                    Verified
                  </Badge>
                </div>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                  <div className="space-y-2">
                    <Label htmlFor="firstName" className="text-sm font-medium flex items-center gap-2">
                      First Name
                      <span className="text-red-500">*</span>
                    </Label>
                    <Input 
                      id="firstName" 
                      value={firstName}
                      onChange={(e) => setFirstName(e.target.value)}
                      placeholder="Enter first name"
                      className="h-11 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-primary"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="lastName" className="text-sm font-medium flex items-center gap-2">
                      Last Name
                      <span className="text-red-500">*</span>
                    </Label>
                    <Input 
                      id="lastName" 
                      value={lastName}
                      onChange={(e) => setLastName(e.target.value)}
                      placeholder="Enter last name"
                      className="h-11 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-primary"
                    />
                  </div>
                </div>
                
                <div className="space-y-2">
                  <Label htmlFor="email" className="text-sm font-medium flex items-center gap-2">
                    <Mail className="h-4 w-4" />
                    Email Address
                    <span className="text-red-500">*</span>
                  </Label>
                  <Input 
                    id="email" 
                    type="email" 
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder="your.email@example.com"
                    className="h-11 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-primary"
                  />
                  <p className="text-xs text-gray-500 flex items-center gap-1">
                    <Info className="h-3 w-3" />
                    We'll send verification emails to this address
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="role" className="text-sm font-medium">Current Role</Label>
                  <div className="flex items-center gap-2">
                    <Input 
                      id="role" 
                      defaultValue={(user as any)?.role || "User"} 
                      disabled 
                      className="h-11 bg-gray-50 dark:bg-gray-900 border-gray-300 dark:border-gray-600"
                    />
                    <Badge variant="outline" className="capitalize">
                      {(user as any)?.role || "user"}
                    </Badge>
                  </div>
                </div>

                <Separator className="my-6" />

                <div className="flex flex-col sm:flex-row gap-3">
                  <Button 
                    className="flex-1 h-11 bg-gradient-to-r from-primary to-primary/80 hover:from-primary/90 hover:to-primary/70 shadow-md hover:shadow-lg transition-all"
                    onClick={handleSaveProfile}
                    disabled={updateProfileMutation.isPending}
                  >
                    {updateProfileMutation.isPending ? (
                      <>
                        <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                        Saving Changes...
                      </>
                    ) : (
                      <>
                        <Save className="h-4 w-4 mr-2" />
                        Save Profile Changes
                      </>
                    )}
                  </Button>
                  <Button 
                    variant="outline"
                    className="sm:w-auto h-11 border-gray-300 dark:border-gray-600"
                  >
                    <RefreshCw className="h-4 w-4 mr-2" />
                    Reset
                  </Button>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Security Tab */}
          <TabsContent value="security" className="space-y-6">
            <Card className="border-0 shadow-xl bg-white dark:bg-gray-800 overflow-hidden">
              <div className="h-2 bg-gradient-to-r from-green-500 via-teal-500 to-cyan-500" />
              <CardHeader>
                <CardTitle className="text-2xl flex items-center gap-2">
                  <Shield className="h-5 w-5 text-green-600" />
                  Security & Privacy
                </CardTitle>
                <CardDescription>
                  Protect your account with advanced security features
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Two-Factor Authentication */}
                <div className="p-4 rounded-lg border border-gray-200 dark:border-gray-700 bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-900/10 dark:to-emerald-900/10">
                  <div className="flex items-center justify-between">
                    <div className="space-y-1 flex-1">
                      <Label className="text-base font-semibold flex items-center gap-2">
                        <Shield className="h-4 w-4 text-green-600" />
                        Two-Factor Authentication
                      </Label>
                      <p className="text-sm text-gray-600 dark:text-gray-400">
                        Add an extra layer of security to your account
                      </p>
                    </div>
                    <div className="flex items-center gap-3">
                      <Badge variant="outline" className="hidden sm:flex">Not Enabled</Badge>
                      <Switch />
                    </div>
                  </div>
                </div>

                <Separator />

                {/* Session Timeout */}
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                  <div className="space-y-1">
                    <Label className="text-base font-medium">Session Timeout</Label>
                    <p className="text-sm text-gray-600 dark:text-gray-400">
                      Automatically log out after period of inactivity
                    </p>
                  </div>
                  <Select defaultValue="30">
                    <SelectTrigger className="w-full sm:w-40 h-10">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="15">15 minutes</SelectItem>
                      <SelectItem value="30">30 minutes</SelectItem>
                      <SelectItem value="60">1 hour</SelectItem>
                      <SelectItem value="240">4 hours</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <Separator />

                {/* Activity Logging */}
                <div className="flex items-center justify-between">
                  <div className="space-y-1">
                    <Label className="text-base font-medium">Activity Logging</Label>
                    <p className="text-sm text-gray-600 dark:text-gray-400">
                      Track user actions and system events for security
                    </p>
                  </div>
                  <Switch defaultChecked />
                </div>

                <Separator />

                {/* Password Change */}
                <div className="space-y-4 p-4 rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50">
                  <Label className="text-base font-semibold flex items-center gap-2">
                    <Lock className="h-4 w-4" />
                    Change Password
                  </Label>
                  <div className="grid grid-cols-1 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="current-password" className="text-sm">Current Password</Label>
                      <Input 
                        id="current-password"
                        type="password" 
                        placeholder="••••••••" 
                        className="h-10"
                      />
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="new-password" className="text-sm">New Password</Label>
                        <Input 
                          id="new-password"
                          type="password" 
                          placeholder="••••••••" 
                          className="h-10"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="confirm-password" className="text-sm">Confirm Password</Label>
                        <Input 
                          id="confirm-password"
                          type="password" 
                          placeholder="••••••••" 
                          className="h-10"
                        />
                      </div>
                    </div>
                    <Button variant="outline" className="w-full sm:w-auto h-10">
                      <Lock className="h-4 w-4 mr-2" />
                      Update Password
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Notifications Tab */}
          <TabsContent value="notifications" className="space-y-6">
            <Card className="border-0 shadow-xl bg-white dark:bg-gray-800 overflow-hidden">
              <div className="h-2 bg-gradient-to-r from-purple-500 via-pink-500 to-rose-500" />
              <CardHeader>
                <CardTitle className="text-2xl flex items-center gap-2">
                  <Bell className="h-5 w-5 text-purple-600" />
                  Notification Preferences
                </CardTitle>
                <CardDescription>
                  Configure how you receive alerts and updates
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Email Notifications */}
                <div className="p-4 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-primary/50 transition-colors">
                  <div className="flex items-center justify-between">
                    <div className="flex items-start gap-3 flex-1">
                      <div className="p-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
                        <Mail className="h-5 w-5 text-blue-600 dark:text-blue-400" />
                      </div>
                      <div className="space-y-1">
                        <Label className="text-base font-medium">Email Notifications</Label>
                        <p className="text-sm text-gray-600 dark:text-gray-400">
                          Receive important updates via email
                        </p>
                      </div>
                    </div>
                    <Switch 
                      checked={emailNotifications} 
                      onCheckedChange={setEmailNotifications} 
                    />
                  </div>
                </div>

                {/* Push Notifications */}
                <div className="p-4 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-primary/50 transition-colors">
                  <div className="flex items-center justify-between">
                    <div className="flex items-start gap-3 flex-1">
                      <div className="p-2 bg-purple-100 dark:bg-purple-900/30 rounded-lg">
                        <Smartphone className="h-5 w-5 text-purple-600 dark:text-purple-400" />
                      </div>
                      <div className="space-y-1">
                        <Label className="text-base font-medium">Push Notifications</Label>
                        <p className="text-sm text-gray-600 dark:text-gray-400">
                          Get instant alerts on your devices
                        </p>
                      </div>
                    </div>
                    <Switch 
                      checked={pushNotifications} 
                      onCheckedChange={setPushNotifications} 
                    />
                  </div>
                </div>

                <Separator />

                {/* Notification Types */}
                <div className="space-y-4">
                  <div className="flex items-center gap-2">
                    <Zap className="h-4 w-4 text-primary" />
                    <Label className="text-base font-semibold">Notification Types</Label>
                  </div>
                  <div className="space-y-3">
                    {[
                      { label: "New player registrations", icon: User, defaultChecked: true },
                      { label: "Team updates and changes", icon: User, defaultChecked: true },
                      { label: "Coach assignments", icon: Shield, defaultChecked: true },
                      { label: "System maintenance alerts", icon: AlertCircle, defaultChecked: false },
                      { label: "Performance reports", icon: ChevronRight, defaultChecked: true },
                    ].map((item, index) => (
                      <div 
                        key={index} 
                        className="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-900/50 transition-colors"
                      >
                        <Label className="text-sm font-normal flex items-center gap-2 cursor-pointer">
                          <item.icon className="h-4 w-4 text-gray-500" />
                          {item.label}
                        </Label>
                        <Switch defaultChecked={item.defaultChecked} />
                      </div>
                    ))}
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Appearance Tab */}
          <TabsContent value="appearance" className="space-y-6">
            <Card className="border-0 shadow-xl bg-white dark:bg-gray-800 overflow-hidden">
              <div className="h-2 bg-gradient-to-r from-orange-500 via-amber-500 to-yellow-500" />
              <CardHeader>
                <CardTitle className="text-2xl flex items-center gap-2">
                  <Palette className="h-5 w-5 text-orange-600" />
                  Appearance & Localization
                </CardTitle>
                <CardDescription>
                  Customize the look and feel of your application
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Theme Selection */}
                <div className="space-y-4">
                  <Label className="text-base font-semibold flex items-center gap-2">
                    {getThemeIcon()}
                    Theme Preference
                  </Label>
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    {[
                      { value: 'light', label: 'Light', icon: Sun, desc: 'Bright and clear' },
                      { value: 'dark', label: 'Dark', icon: Moon, desc: 'Easy on the eyes' },
                      { value: 'system', label: 'System', icon: Monitor, desc: 'Match your OS' }
                    ].map((themeOption) => (
                      <button
                        key={themeOption.value}
                        onClick={() => setTheme(themeOption.value as "light" | "dark" | "system")}
                        className={`p-4 rounded-lg border-2 transition-all hover:shadow-md ${
                          theme === themeOption.value
                            ? 'border-primary bg-primary/5 shadow-lg'
                            : 'border-gray-200 dark:border-gray-700 hover:border-primary/50'
                        }`}
                      >
                        <div className="flex flex-col items-center gap-2 text-center">
                          <themeOption.icon className={`h-6 w-6 ${theme === themeOption.value ? 'text-primary' : 'text-gray-500'}`} />
                          <div>
                            <p className="font-medium">{themeOption.label}</p>
                            <p className="text-xs text-gray-500">{themeOption.desc}</p>
                          </div>
                          {theme === themeOption.value && (
                            <Badge variant="default" className="text-xs">
                              <Check className="h-3 w-3 mr-1" />
                              Active
                            </Badge>
                          )}
                        </div>
                      </button>
                    ))}
                  </div>
                </div>

                <Separator />

                {/* Language and Timezone */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                  <div className="space-y-3">
                    <Label className="text-base font-medium flex items-center gap-2">
                      <Globe className="h-4 w-4" />
                      Language
                    </Label>
                    <Select value={language} onValueChange={setLanguage}>
                      <SelectTrigger className="h-11">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="en">🇬🇧 English</SelectItem>
                        <SelectItem value="es">🇪🇸 Spanish</SelectItem>
                        <SelectItem value="fr">🇫🇷 French</SelectItem>
                        <SelectItem value="de">🇩🇪 German</SelectItem>
                        <SelectItem value="it">🇮🇹 Italian</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-3">
                    <Label className="text-base font-medium">Timezone</Label>
                    <Select value={timezone} onValueChange={setTimezone}>
                      <SelectTrigger className="h-11">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="UTC">UTC (GMT+0)</SelectItem>
                        <SelectItem value="EST">Eastern Time (GMT-5)</SelectItem>
                        <SelectItem value="CST">Central Time (GMT-6)</SelectItem>
                        <SelectItem value="MST">Mountain Time (GMT-7)</SelectItem>
                        <SelectItem value="PST">Pacific Time (GMT-8)</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Accessibility Tab */}
          <TabsContent value="accessibility" className="space-y-6">
            <Card className="border-0 shadow-xl bg-white dark:bg-gray-800 overflow-hidden">
              <div className="h-2 bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500" />
              <CardHeader>
                <CardTitle className="text-2xl flex items-center gap-2">
                  <Accessibility className="h-5 w-5 text-indigo-600" />
                  Accessibility Features
                </CardTitle>
                <CardDescription>
                  Customize accessibility features for a better experience
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {[
                  { 
                    key: 'highContrast', 
                    icon: Eye, 
                    label: 'High Contrast Mode', 
                    desc: 'Increase contrast for better visibility',
                    color: 'blue'
                  },
                  { 
                    key: 'reducedMotion', 
                    icon: Volume2, 
                    label: 'Reduced Motion', 
                    desc: 'Minimize animations and transitions',
                    color: 'green'
                  },
                  { 
                    key: 'largeText', 
                    icon: Type, 
                    label: 'Large Text', 
                    desc: 'Increase font size throughout the application',
                    color: 'purple'
                  },
                  { 
                    key: 'screenReaderMode', 
                    icon: Volume2, 
                    label: 'Screen Reader Mode', 
                    desc: 'Enhanced support for screen reading software',
                    color: 'orange'
                  },
                  { 
                    key: 'keyboardNavigation', 
                    icon: Keyboard, 
                    label: 'Enhanced Keyboard Navigation', 
                    desc: 'Improved focus indicators and keyboard shortcuts',
                    color: 'pink'
                  },
                ].map((setting) => (
                  <div 
                    key={setting.key}
                    className="p-4 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-primary/50 transition-colors"
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-start gap-3 flex-1">
                        <div className={`p-2 bg-${setting.color}-100 dark:bg-${setting.color}-900/30 rounded-lg`}>
                          <setting.icon className={`h-5 w-5 text-${setting.color}-600 dark:text-${setting.color}-400`} />
                        </div>
                        <div className="space-y-1">
                          <Label className="text-base font-medium">{setting.label}</Label>
                          <p className="text-sm text-gray-600 dark:text-gray-400">{setting.desc}</p>
                        </div>
                      </div>
                      <Switch 
                        checked={accessibilitySettings[setting.key as keyof typeof accessibilitySettings]} 
                        onCheckedChange={(checked) => updateAccessibilitySetting(setting.key as keyof typeof accessibilitySettings, checked)} 
                      />
                    </div>
                  </div>
                ))}

                <Separator />

                <div className="p-4 rounded-lg bg-gray-50 dark:bg-gray-900/50 border border-gray-200 dark:border-gray-700">
                  <div className="flex items-start gap-3 mb-3">
                    <Info className="h-5 w-5 text-blue-600 mt-0.5" />
                    <div>
                      <Label className="text-base font-medium">Reset Accessibility Settings</Label>
                      <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                        This will reset all accessibility settings to their default values
                      </p>
                    </div>
                  </div>
                  <Button 
                    variant="outline" 
                    className="w-full sm:w-auto h-10"
                    onClick={resetAccessibilitySettings}
                  >
                    <RefreshCw className="h-4 w-4 mr-2" />
                    Reset to Defaults
                  </Button>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Data Management Tab */}
          <TabsContent value="data" className="space-y-6">
            <Card className="border-0 shadow-xl bg-white dark:bg-gray-800 overflow-hidden">
              <div className="h-2 bg-gradient-to-r from-cyan-500 via-teal-500 to-green-500" />
              <CardHeader>
                <CardTitle className="text-2xl flex items-center gap-2">
                  <Database className="h-5 w-5 text-cyan-600" />
                  Data Management
                </CardTitle>
                <CardDescription>
                  Import, export, and manage your application data
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                  {/* Export Data */}
                  <div className="p-6 rounded-lg border-2 border-dashed border-gray-300 dark:border-gray-700 hover:border-primary/50 hover:bg-primary/5 transition-all group">
                    <div className="text-center space-y-4">
                      <div className="mx-auto w-16 h-16 bg-gradient-to-br from-blue-500 to-cyan-500 rounded-xl flex items-center justify-center group-hover:scale-110 transition-transform shadow-lg">
                        <Download className="h-8 w-8 text-white" />
                      </div>
                      <div>
                        <h3 className="font-semibold text-lg mb-2">Export Data</h3>
                        <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
                          Download all your application data as a JSON file
                        </p>
                      </div>
                      <Button 
                        className="w-full h-11 bg-gradient-to-r from-blue-500 to-cyan-500 hover:from-blue-600 hover:to-cyan-600"
                        onClick={handleExportData}
                        disabled={isExporting}
                      >
                        {isExporting ? (
                          <>
                            <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                            Exporting...
                          </>
                        ) : (
                          <>
                            <Download className="h-4 w-4 mr-2" />
                            Export Data
                          </>
                        )}
                      </Button>
                    </div>
                  </div>

                  {/* Import Data */}
                  <div className="p-6 rounded-lg border-2 border-dashed border-gray-300 dark:border-gray-700 hover:border-primary/50 hover:bg-primary/5 transition-all group">
                    <div className="text-center space-y-4">
                      <div className="mx-auto w-16 h-16 bg-gradient-to-br from-green-500 to-teal-500 rounded-xl flex items-center justify-center group-hover:scale-110 transition-transform shadow-lg">
                        <Upload className="h-8 w-8 text-white" />
                      </div>
                      <div>
                        <h3 className="font-semibold text-lg mb-2">Import Data</h3>
                        <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
                          Upload a JSON file to restore your data
                        </p>
                      </div>
                      <input
                        type="file"
                        ref={fileInputRef}
                        onChange={handleImportData}
                        accept=".json"
                        className="hidden"
                      />
                      <Button 
                        className="w-full h-11 bg-gradient-to-r from-green-500 to-teal-500 hover:from-green-600 hover:to-teal-600"
                        onClick={() => fileInputRef.current?.click()}
                        disabled={isImporting}
                      >
                        {isImporting ? (
                          <>
                            <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                            Importing...
                          </>
                        ) : (
                          <>
                            <Upload className="h-4 w-4 mr-2" />
                            Import Data
                          </>
                        )}
                      </Button>
                    </div>
                  </div>
                </div>

                <div className="p-4 rounded-lg bg-amber-50 dark:bg-amber-900/10 border border-amber-200 dark:border-amber-800">
                  <div className="flex items-start gap-3">
                    <AlertCircle className="h-5 w-5 text-amber-600 dark:text-amber-500 mt-0.5" />
                    <div className="flex-1">
                      <h4 className="font-medium text-amber-900 dark:text-amber-200 mb-1">Important Notice</h4>
                      <p className="text-sm text-amber-800 dark:text-amber-300">
                        Importing data will overwrite existing records. Please ensure you have a backup before proceeding.
                      </p>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}
