import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { queryClient, apiRequest } from "@/lib/queryClient";
import { useAuth } from "@/hooks/use-auth";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Settings as SettingsIcon, Bell, Sparkles, Globe, Languages } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

export default function Settings() {
  const { user } = useAuth();
  const { toast } = useToast();

  const [notificationsEnabled, setNotificationsEnabled] = useState(user?.notificationsEnabled ?? true);
  const [aiSuggestionsEnabled, setAiSuggestionsEnabled] = useState(user?.aiSuggestionsEnabled ?? true);
  const [timezone, setTimezone] = useState(user?.timezone || "UTC");
  const [language, setLanguage] = useState(user?.language || "en");

  const updateSettingsMutation = useMutation({
    mutationFn: async (settings: {
      notificationsEnabled?: boolean;
      aiSuggestionsEnabled?: boolean;
      timezone?: string;
      language?: string;
    }) => {
      return apiRequest("PATCH", "/api/user/settings", settings);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/user"] });
      toast({
        title: "Settings saved",
        description: "Your preferences have been updated successfully.",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to save settings. Please try again.",
        variant: "destructive",
      });
    },
  });

  const handleNotificationsToggle = (value: boolean) => {
    setNotificationsEnabled(value);
    updateSettingsMutation.mutate({ notificationsEnabled: value });
  };

  const handleAiSuggestionsToggle = (value: boolean) => {
    setAiSuggestionsEnabled(value);
    updateSettingsMutation.mutate({ aiSuggestionsEnabled: value });
  };

  const handleTimezoneChange = (value: string) => {
    setTimezone(value);
    updateSettingsMutation.mutate({ timezone: value });
  };

  const handleLanguageChange = (value: string) => {
    setLanguage(value);
    updateSettingsMutation.mutate({ language: value });
  };

  const timezones = [
    { value: "UTC", label: "UTC" },
    { value: "America/New_York", label: "Eastern Time (ET)" },
    { value: "America/Chicago", label: "Central Time (CT)" },
    { value: "America/Denver", label: "Mountain Time (MT)" },
    { value: "America/Los_Angeles", label: "Pacific Time (PT)" },
    { value: "Europe/London", label: "London (GMT)" },
    { value: "Europe/Paris", label: "Paris (CET)" },
    { value: "Asia/Tokyo", label: "Tokyo (JST)" },
    { value: "Asia/Shanghai", label: "Shanghai (CST)" },
    { value: "Australia/Sydney", label: "Sydney (AEDT)" },
  ];

  const languages = [
    { value: "en", label: "English" },
    { value: "es", label: "Spanish" },
    { value: "fr", label: "French" },
    { value: "de", label: "German" },
    { value: "zh", label: "Chinese" },
    { value: "ja", label: "Japanese" },
  ];

  return (
    <div className="min-h-screen p-6">
      {/* Header */}
      <div className="max-w-5xl mx-auto mb-6">
        <div className="flex items-center gap-3 mb-2">
          <div className="p-3 rounded-xl bg-gradient-to-br from-indigo-500 to-purple-600">
            <SettingsIcon className="h-6 w-6 text-white" />
          </div>
          <div>
            <h1 className="text-2xl font-bold bg-gradient-to-r from-indigo-400 to-purple-400 bg-clip-text text-transparent">
              Settings
            </h1>
            <p className="text-sm text-muted-foreground">
              Manage your account preferences
            </p>
          </div>
        </div>
      </div>

      {/* Settings Sections */}
      <div className="max-w-5xl mx-auto space-y-6">
        {/* Notifications */}
        <Card className="p-6">
          <div className="flex items-start justify-between">
            <div className="flex items-start gap-4 flex-1">
              <div className="p-2 rounded-lg bg-indigo-500/10">
                <Bell className="h-5 w-5 text-indigo-500" />
              </div>
              <div className="flex-1">
                <h3 className="font-semibold mb-1">Notifications</h3>
                <p className="text-sm text-muted-foreground">
                  Receive email notifications for plan updates and reminders
                </p>
              </div>
            </div>
            <Switch
              checked={notificationsEnabled}
              onCheckedChange={handleNotificationsToggle}
              disabled={updateSettingsMutation.isPending}
              data-testid="switch-notifications"
            />
          </div>
        </Card>

        {/* AI Suggestions */}
        <Card className="p-6">
          <div className="flex items-start justify-between">
            <div className="flex items-start gap-4 flex-1">
              <div className="p-2 rounded-lg bg-purple-500/10">
                <Sparkles className="h-5 w-5 text-purple-500" />
              </div>
              <div className="flex-1">
                <h3 className="font-semibold mb-1">AI Suggestions</h3>
                <p className="text-sm text-muted-foreground">
                  Enable AI-powered suggestions and recommendations for your plans
                </p>
              </div>
            </div>
            <Switch
              checked={aiSuggestionsEnabled}
              onCheckedChange={handleAiSuggestionsToggle}
              disabled={updateSettingsMutation.isPending}
              data-testid="switch-ai-suggestions"
            />
          </div>
        </Card>

        {/* Timezone */}
        <Card className="p-6">
          <div className="flex items-start gap-4">
            <div className="p-2 rounded-lg bg-teal-500/10 flex-shrink-0">
              <Globe className="h-5 w-5 text-teal-500" />
            </div>
            <div className="flex-1">
              <h3 className="font-semibold mb-1">Timezone</h3>
              <p className="text-sm text-muted-foreground mb-4">
                Set your timezone for accurate date and time displays
              </p>
              <Select
                value={timezone}
                onValueChange={handleTimezoneChange}
                disabled={updateSettingsMutation.isPending}
              >
                <SelectTrigger className="max-w-sm" data-testid="select-timezone">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {timezones.map((tz) => (
                    <SelectItem key={tz.value} value={tz.value}>
                      {tz.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </Card>

        {/* Language */}
        <Card className="p-6">
          <div className="flex items-start gap-4">
            <div className="p-2 rounded-lg bg-indigo-500/10 flex-shrink-0">
              <Languages className="h-5 w-5 text-indigo-500" />
            </div>
            <div className="flex-1">
              <h3 className="font-semibold mb-1">Language</h3>
              <p className="text-sm text-muted-foreground mb-4">
                Choose your preferred language for the interface
              </p>
              <Select
                value={language}
                onValueChange={handleLanguageChange}
                disabled={updateSettingsMutation.isPending}
              >
                <SelectTrigger className="max-w-sm" data-testid="select-language">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {languages.map((lang) => (
                    <SelectItem key={lang.value} value={lang.value}>
                      {lang.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </Card>

        {/* Account Information */}
        <Card className="p-6">
          <h3 className="font-semibold mb-4">Account Information</h3>
          <div className="space-y-3">
            <div>
              <p className="text-sm text-muted-foreground">Email</p>
              <p className="font-medium" data-testid="text-user-email">{user?.email}</p>
            </div>
            <div>
              <p className="text-sm text-muted-foreground">Name</p>
              <p className="font-medium" data-testid="text-user-name">
                {user?.firstName} {user?.lastName}
              </p>
            </div>
            <div>
              <p className="text-sm text-muted-foreground">Plan Limit</p>
              <p className="font-medium" data-testid="text-plan-limit">{user?.planLimit || 10} plans</p>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
}
