import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";
import { Globe, Clock, Save, MapPin } from "lucide-react";

const languages = [
  { code: "en", name: "English", flag: "🇺🇸" },
  { code: "es", name: "Español", flag: "🇪🇸" },
  { code: "fr", name: "Français", flag: "🇫🇷" },
  { code: "de", name: "Deutsch", flag: "🇩🇪" },
  { code: "it", name: "Italiano", flag: "🇮🇹" },
  { code: "pt", name: "Português", flag: "🇵🇹" },
  { code: "zh", name: "中文", flag: "🇨🇳" },
  { code: "ja", name: "日本語", flag: "🇯🇵" },
  { code: "ko", name: "한국어", flag: "🇰🇷" },
  { code: "ar", name: "العربية", flag: "🇸🇦" }
];

const timezones = [
  { value: "UTC", label: "UTC - Coordinated Universal Time" },
  { 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: "British Time (GMT/BST)" },
  { value: "Europe/Paris", label: "Central European Time (CET)" },
  { value: "Europe/Berlin", label: "Central European Time (CET)" },
  { value: "Europe/Rome", label: "Central European Time (CET)" },
  { value: "Asia/Tokyo", label: "Japan Standard Time (JST)" },
  { value: "Asia/Shanghai", label: "China Standard Time (CST)" },
  { value: "Asia/Seoul", label: "Korea Standard Time (KST)" },
  { value: "Asia/Dubai", label: "Gulf Standard Time (GST)" },
  { value: "Australia/Sydney", label: "Australian Eastern Time (AET)" },
  { value: "Australia/Melbourne", label: "Australian Eastern Time (AET)" }
];

const dateFormats = [
  { value: "MM/DD/YYYY", label: "MM/DD/YYYY (US Format)" },
  { value: "DD/MM/YYYY", label: "DD/MM/YYYY (European Format)" },
  { value: "YYYY-MM-DD", label: "YYYY-MM-DD (ISO Format)" },
  { value: "DD-MMM-YYYY", label: "DD-MMM-YYYY (e.g., 15-Jan-2024)" }
];

const timeFormats = [
  { value: "12h", label: "12-hour (e.g., 2:30 PM)" },
  { value: "24h", label: "24-hour (e.g., 14:30)" }
];

export default function LanguageSettings() {
  const { toast } = useToast();
  const [settings, setSettings] = useState({
    language: "en",
    timezone: "UTC",
    dateFormat: "MM/DD/YYYY",
    timeFormat: "12h",
    autoDetectLocation: true
  });
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    // Load user's current settings
    const savedLanguage = localStorage.getItem("userLanguage") || "en";
    const savedTimezone = localStorage.getItem("userTimezone") || Intl.DateTimeFormat().resolvedOptions().timeZone;
    const savedDateFormat = localStorage.getItem("userDateFormat") || "MM/DD/YYYY";
    const savedTimeFormat = localStorage.getItem("userTimeFormat") || "12h";
    
    setSettings({
      language: savedLanguage,
      timezone: savedTimezone,
      dateFormat: savedDateFormat,
      timeFormat: savedTimeFormat,
      autoDetectLocation: localStorage.getItem("autoDetectLocation") !== "false"
    });
  }, []);

  const handleSave = async () => {
    setIsLoading(true);
    try {
      // Save to localStorage
      localStorage.setItem("userLanguage", settings.language);
      localStorage.setItem("userTimezone", settings.timezone);
      localStorage.setItem("userDateFormat", settings.dateFormat);
      localStorage.setItem("userTimeFormat", settings.timeFormat);
      localStorage.setItem("autoDetectLocation", settings.autoDetectLocation.toString());

      // In a real app, you would also save to the server/database
      // await apiRequest("PUT", "/api/user/language-settings", settings);

      toast({
        title: "Settings Saved",
        description: "Your language and timezone preferences have been updated.",
      });
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to save settings. Please try again.",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  };

  const detectUserLocation = () => {
    if ("geolocation" in navigator) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          // In a real app, you would use a service to convert coordinates to timezone
          const detectedTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
          setSettings({ ...settings, timezone: detectedTimezone });
          toast({
            title: "Location Detected",
            description: `Timezone updated to ${detectedTimezone}`,
          });
        },
        (error) => {
          toast({
            title: "Location Error",
            description: "Unable to detect your location. Please select manually.",
            variant: "destructive",
          });
        }
      );
    }
  };

  return (
    <div className="container mx-auto px-6 py-8">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-foreground flex items-center gap-3">
          <Globe className="w-8 h-8 text-primary" />
          Language & Timezone Settings
        </h1>
        <p className="text-muted-foreground mt-2">
          Configure your language preferences and timezone settings
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Language Settings */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Globe className="w-5 h-5" />
              Language Preferences
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="language">Display Language</Label>
              <Select
                value={settings.language}
                onValueChange={(value) => setSettings({ ...settings, language: value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select language" />
                </SelectTrigger>
                <SelectContent>
                  {languages.map((lang) => (
                    <SelectItem key={lang.code} value={lang.code}>
                      <span className="flex items-center gap-2">
                        <span>{lang.flag}</span>
                        <span>{lang.name}</span>
                      </span>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>

        {/* Timezone Settings */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Clock className="w-5 h-5" />
              Timezone Settings
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="timezone">Timezone</Label>
              <div className="flex gap-2">
                <Select
                  value={settings.timezone}
                  onValueChange={(value) => setSettings({ ...settings, timezone: value })}
                >
                  <SelectTrigger className="flex-1">
                    <SelectValue placeholder="Select timezone" />
                  </SelectTrigger>
                  <SelectContent>
                    {timezones.map((tz) => (
                      <SelectItem key={tz.value} value={tz.value}>
                        {tz.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <Button
                  variant="outline"
                  size="icon"
                  onClick={detectUserLocation}
                  title="Auto-detect timezone"
                >
                  <MapPin className="w-4 h-4" />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Date & Time Format */}
        <Card>
          <CardHeader>
            <CardTitle>Date & Time Formats</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="dateFormat">Date Format</Label>
              <Select
                value={settings.dateFormat}
                onValueChange={(value) => setSettings({ ...settings, dateFormat: value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select date format" />
                </SelectTrigger>
                <SelectContent>
                  {dateFormats.map((format) => (
                    <SelectItem key={format.value} value={format.value}>
                      {format.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="timeFormat">Time Format</Label>
              <Select
                value={settings.timeFormat}
                onValueChange={(value) => setSettings({ ...settings, timeFormat: value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select time format" />
                </SelectTrigger>
                <SelectContent>
                  {timeFormats.map((format) => (
                    <SelectItem key={format.value} value={format.value}>
                      {format.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>

        {/* Preview */}
        <Card>
          <CardHeader>
            <CardTitle>Preview</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="p-4 bg-muted rounded-lg space-y-2">
              <p><strong>Language:</strong> {languages.find(l => l.code === settings.language)?.name}</p>
              <p><strong>Timezone:</strong> {settings.timezone}</p>
              <p><strong>Current Date:</strong> {
                settings.dateFormat === "MM/DD/YYYY" ? "01/15/2024" :
                settings.dateFormat === "DD/MM/YYYY" ? "15/01/2024" :
                settings.dateFormat === "YYYY-MM-DD" ? "2024-01-15" :
                "15-Jan-2024"
              }</p>
              <p><strong>Current Time:</strong> {
                settings.timeFormat === "12h" ? "2:30 PM" : "14:30"
              }</p>
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="mt-8 flex justify-end">
        <Button onClick={handleSave} disabled={isLoading} className="min-w-[120px]">
          {isLoading ? (
            <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
          ) : (
            <>
              <Save className="w-4 h-4 mr-2" />
              Save Settings
            </>
          )}
        </Button>
      </div>
    </div>
  );
}