import { useState, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Sun, Moon, Monitor } from 'lucide-react';
import { trpc } from '@/lib/trpc';
import { useNotify } from '@/hooks/useNotify';
import { usePlatform } from '@/lib/platform';
import { useTheme } from '@/components/theme-provider';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { SettingsCard } from './SettingsCard';
import { SUPPORTED_LANGUAGES } from '@/i18n';

const THEME_OPTIONS = [
  { value: 'light', icon: Sun, labelKey: 'settings.themeLight' },
  { value: 'dark', icon: Moon, labelKey: 'settings.themeDark' },
  { value: 'system', icon: Monitor, labelKey: 'settings.themeSystem' },
] as const;

export function AppearanceSection() {
  const { t, i18n } = useTranslation();
  const { theme, setTheme } = useTheme();
  const platform = usePlatform();
  const uiLanguageQuery = trpc.settings.getUiLanguage.useQuery();
  const setUiLanguageMutation = trpc.settings.setUiLanguage.useMutation();
  const updateMemoryMutation = trpc.auth.updateMemory.useMutation();
  const formatPrefsQuery = trpc.settings.getFormatPrefs.useQuery();
  const setFormatPrefsMutation = trpc.settings.setFormatPrefs.useMutation();
  const utils = trpc.useUtils();
  const { notify } = useNotify();

  // Display prefs (device-local)
  const [timezone, setTimezone] = useState('');
  const [dateFormat, setDateFormat] = useState('dd/MM/yyyy');
  const [timeFormat, setTimeFormat] = useState<'12h' | '24h'>('24h');

  useEffect(() => {
    if (formatPrefsQuery.data) {
      setTimezone(formatPrefsQuery.data.timezone);
      setDateFormat(formatPrefsQuery.data.dateFormat);
      setTimeFormat(formatPrefsQuery.data.timeFormat);
    }
  }, [formatPrefsQuery.data]);

  const timezones = useMemo(() => {
    try {
      return Intl.supportedValuesOf('timeZone');
    } catch {
      return ['UTC'];
    }
  }, []);

  function handleLanguageChange(lang: string) {
    void i18n.changeLanguage(lang);
    setUiLanguageMutation.mutate({ lang });
    notify('info', 'toast.settings.languageChanged');
    updateMemoryMutation.mutate(
      {
        memory: { language: SUPPORTED_LANGUAGES.find((l) => l.code === lang)?.label ?? lang },
        markOnboarded: false,
      },
      { onSuccess: () => void utils.auth.status.invalidate() },
    );
  }

  function handleSaveDisplay() {
    setFormatPrefsMutation.mutate(
      { timezone, dateFormat, timeFormat },
      {
        onSuccess: () => {
          notify('success', 'toast.settings.formatPrefsSaved');
          void utils.settings.getFormatPrefs.invalidate();
        },
      },
    );
  }

  return (
    <>
      {/* Theme */}
      <SettingsCard title={t('settings.theme')} description={t('settings.themeDescription')}>
        <div className="flex gap-2">
          {THEME_OPTIONS.map(({ value, icon: Icon, labelKey }) => (
            <Button
              key={value}
              variant={theme === value ? 'default' : 'outline'}
              size="sm"
              onClick={() => setTheme(value)}
              className="gap-2"
            >
              <Icon data-icon="inline-start" />
              {t(labelKey)}
            </Button>
          ))}
        </div>
      </SettingsCard>

      {/* Interface language */}
      <SettingsCard title={t('settings.uiLanguage')} description={t('settings.uiLanguageDescription')}>
        <Select value={uiLanguageQuery.data ?? 'en'} onValueChange={handleLanguageChange}>
          <SelectTrigger className="w-full">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {SUPPORTED_LANGUAGES.map((lang) => (
              <SelectItem key={lang.code} value={lang.code}>
                {lang.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </SettingsCard>

      <Separator />

      {/* Display preferences — device-local */}
      {platform.isElectron && (
        <SettingsCard
          title={t('settings.displayPreferences')}
          description={t('settings.displayPreferencesDescription')}
        >
          <div className="flex flex-col gap-4">
            <div className="flex flex-col gap-1.5">
              <Label htmlFor="timezone" className="text-xs">{t('settings.timezone')}</Label>
              <Select value={timezone} onValueChange={setTimezone}>
                <SelectTrigger id="timezone" className="w-full">
                  <SelectValue placeholder={t('settings.timezonePlaceholder')} />
                </SelectTrigger>
                <SelectContent className="max-h-60">
                  {timezones.map((tz) => (
                    <SelectItem key={tz} value={tz}>{tz}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="flex flex-col gap-1.5">
              <Label htmlFor="dateFormat" className="text-xs">{t('settings.dateFormat')}</Label>
              <Select value={dateFormat} onValueChange={setDateFormat}>
                <SelectTrigger id="dateFormat" className="w-full">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="dd/MM/yyyy">dd/MM/yyyy</SelectItem>
                  <SelectItem value="MM/dd/yyyy">MM/dd/yyyy</SelectItem>
                  <SelectItem value="yyyy-MM-dd">yyyy-MM-dd</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="flex flex-col gap-1.5">
              <Label className="text-xs">{t('settings.timeFormat')}</Label>
              <div className="flex gap-2">
                <Button
                  variant={timeFormat === '12h' ? 'default' : 'outline'}
                  size="sm"
                  onClick={() => setTimeFormat('12h')}
                >
                  12h
                </Button>
                <Button
                  variant={timeFormat === '24h' ? 'default' : 'outline'}
                  size="sm"
                  onClick={() => setTimeFormat('24h')}
                >
                  24h
                </Button>
              </div>
            </div>

            <Button
              size="sm"
              className="w-fit"
              onClick={handleSaveDisplay}
              disabled={setFormatPrefsMutation.isPending}
            >
              {t('common.save')}
            </Button>
          </div>
        </SettingsCard>
      )}
    </>
  );
}
