'use client';

import * as React from 'react';
import { useTheme, type ThemeMode } from '@/features/theme';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/features/shared/components/ui/card';
import { Select } from '@/features/shared/components/ui/select';
import { Switch } from '@/features/shared/components/ui/switch';
import { Button } from '@/features/shared/components/ui/button';
import { useTranslations } from 'next-intl';
import { useI18n } from '@/features/theme';
import { type Locale } from '@/features/theme/i18n-config';

/**
 * EN: Language options for preferences
 * VI: Các tùy chọn ngôn ngữ cho preferences
 */
type Language = 'en' | 'vi';

/**
 * EN: Font size options for chat
 * VI: Các tùy chọn kích thước font cho chat
 */
type FontSize = 'small' | 'medium' | 'large' | 'xlarge';

/**
 * EN: Message grouping options
 * VI: Các tùy chọn nhóm tin nhắn
 */
type MessageGrouping = 'none' | 'by-author' | 'by-time';

/**
 * EN: Preferences interface
 * VI: Interface cho preferences
 */
interface Preferences {
  language: Language;
  theme: ThemeMode;
  chatAutoScroll: boolean;
  chatShowTimestamps: boolean;
  chatMessageGrouping: MessageGrouping;
  chatFontSize: FontSize;
  accessibilityHighContrast: boolean;
  accessibilityScreenReader: boolean;
}

/**
 * EN: Default preferences
 * VI: Preferences mặc định
 */
const defaultPreferences: Preferences = {
  language: 'en',
  theme: 'system',
  chatAutoScroll: true,
  chatShowTimestamps: true,
  chatMessageGrouping: 'by-author',
  chatFontSize: 'medium',
  accessibilityHighContrast: false,
  accessibilityScreenReader: false,
};

/**
 * EN: Preferences page component
 * VI: Component trang Preferences
 *
 * Features:
 * - Language selection
 * - Theme selection (Dark/Light/Auto)
 * - Chat settings (Auto-scroll, Show timestamps, Message grouping, Font size)
 * - Accessibility options (High contrast mode, Screen reader optimizations)
 */
export default function PreferencesPage() {
  // EN: Translation hook / VI: Hook translation
  const t = useTranslations();
  const { locale, setLocale } = useI18n();
  const { theme, setTheme } = useTheme();
  const [preferences, setPreferences] = React.useState<Preferences>(defaultPreferences);
  const [isSaving, setIsSaving] = React.useState(false);
  const [saveSuccess, setSaveSuccess] = React.useState(false);

  // EN: Load preferences from localStorage on mount / VI: Load preferences từ localStorage khi mount
  React.useEffect(() => {
    if (typeof window === 'undefined') return;

    const stored = localStorage.getItem('preferences');
    if (stored) {
      try {
        const parsed = JSON.parse(stored) as Partial<Preferences>;
        const loaded = { ...defaultPreferences, ...parsed, theme, language: locale as Language };
        setPreferences(loaded);
      } catch {
        // EN: Invalid stored data, use defaults / VI: Dữ liệu lưu không hợp lệ, dùng mặc định
        setPreferences({ ...defaultPreferences, theme, language: locale as Language });
      }
    } else {
      setPreferences({ ...defaultPreferences, theme, language: locale as Language });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // EN: Only run on mount / VI: Chỉ chạy khi mount

  // EN: Sync locale with preferences / VI: Đồng bộ locale với preferences
  React.useEffect(() => {
    if (preferences.language !== locale) {
      setPreferences((prev) => ({ ...prev, language: locale as Language }));
    }
  }, [locale, preferences.language]);

  // EN: Update preferences state / VI: Cập nhật state preferences
  const updatePreference = <K extends keyof Preferences>(
    key: K,
    value: Preferences[K]
  ) => {
    setPreferences((prev) => ({ ...prev, [key]: value }));
  };

  // EN: Handle save preferences / VI: Xử lý lưu preferences
  const handleSave = async () => {
    setIsSaving(true);
    setSaveSuccess(false);

    try {
      // EN: Save to localStorage / VI: Lưu vào localStorage
      localStorage.setItem('preferences', JSON.stringify(preferences));
      
      // EN: Show success message / VI: Hiển thị thông báo thành công
      setSaveSuccess(true);
      setTimeout(() => setSaveSuccess(false), 3000);
    } catch (error) {
      console.error('Failed to save preferences:', error);
    } finally {
      setIsSaving(false);
    }
  };

  // EN: Handle theme change / VI: Xử lý thay đổi theme
  const handleThemeChange = (newTheme: ThemeMode) => {
    setTheme(newTheme);
    updatePreference('theme', newTheme);
  };

  // EN: Handle language change / VI: Xử lý thay đổi ngôn ngữ
  const handleLanguageChange = (newLanguage: string) => {
    const lang = newLanguage as Locale;
    setLocale(lang);
    updatePreference('language', lang as Language);
    // EN: Trigger a re-render by updating preferences / VI: Kích hoạt re-render bằng cách cập nhật preferences
    setPreferences((prev) => ({ ...prev, language: lang as Language }));
  };

  return (
    <div className="space-y-6">
      {/* EN: Page header / VI: Header trang */}
      <div>
        <h2 className="text-2xl font-semibold text-text-primary">
          {t('settings.preferences.title')}
        </h2>
        <p className="mt-1 text-sm text-text-tertiary">
          {t('settings.preferences.description')}
        </p>
      </div>

      {/* EN: Language & Theme Section / VI: Phần Ngôn ngữ & Theme */}
      <Card>
        <CardHeader>
          <CardTitle>{t('settings.preferences.languageAndTheme')}</CardTitle>
          <CardDescription>
            {t('settings.preferences.languageAndThemeDesc')}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* EN: Language selection / VI: Chọn ngôn ngữ */}
          <div>
            <Select
              label={t('settings.preferences.language')}
              value={preferences.language}
              onChange={(e) => handleLanguageChange(e.target.value)}
              helperText={t('settings.preferences.languageHelper')}
            >
              <option value="en">English</option>
              <option value="vi">Tiếng Việt</option>
            </Select>
          </div>

          {/* EN: Theme selection / VI: Chọn theme */}
          <div>
            <Select
              label={t('settings.preferences.theme')}
              value={preferences.theme}
              onChange={(e) => handleThemeChange(e.target.value as ThemeMode)}
              helperText={t('settings.preferences.themeHelper')}
            >
              <option value="light">{t('settings.preferences.light')}</option>
              <option value="dark">{t('settings.preferences.dark')}</option>
              <option value="system">{t('settings.preferences.system')}</option>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* EN: Chat Settings Section / VI: Phần Cài đặt Chat */}
      <Card>
        <CardHeader>
          <CardTitle>{t('settings.preferences.chatSettings')}</CardTitle>
          <CardDescription>
            {t('settings.preferences.chatSettingsDesc')}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* EN: Auto-scroll toggle / VI: Toggle tự động cuộn */}
          <div className="flex items-center justify-between">
            <div className="flex-1">
              <label
                htmlFor="chat-auto-scroll"
                className="text-sm font-medium text-text-primary cursor-pointer"
              >
                {t('settings.preferences.autoScroll')}
              </label>
              <p className="mt-1 text-sm text-text-tertiary">
                {t('settings.preferences.autoScrollDesc')}
              </p>
            </div>
            <Switch
              id="chat-auto-scroll"
              checked={preferences.chatAutoScroll}
              onCheckedChange={(checked) => updatePreference('chatAutoScroll', checked)}
            />
          </div>

          {/* EN: Show timestamps toggle / VI: Toggle hiển thị thời gian */}
          <div className="flex items-center justify-between">
            <div className="flex-1">
              <label
                htmlFor="chat-show-timestamps"
                className="text-sm font-medium text-text-primary cursor-pointer"
              >
                {t('settings.preferences.showTimestamps')}
              </label>
              <p className="mt-1 text-sm text-text-tertiary">
                {t('settings.preferences.showTimestampsDesc')}
              </p>
            </div>
            <Switch
              id="chat-show-timestamps"
              checked={preferences.chatShowTimestamps}
              onCheckedChange={(checked) => updatePreference('chatShowTimestamps', checked)}
            />
          </div>

          {/* EN: Message grouping / VI: Nhóm tin nhắn */}
          <div>
            <Select
              label={t('settings.preferences.messageGrouping')}
              value={preferences.chatMessageGrouping}
              onChange={(e) => updatePreference('chatMessageGrouping', e.target.value as MessageGrouping)}
              helperText={t('settings.preferences.messageGroupingHelper')}
            >
              <option value="none">{t('settings.preferences.none')}</option>
              <option value="by-author">{t('settings.preferences.byAuthor')}</option>
              <option value="by-time">{t('settings.preferences.byTime')}</option>
            </Select>
          </div>

          {/* EN: Font size / VI: Kích thước font */}
          <div>
            <Select
              label={t('settings.preferences.fontSize')}
              value={preferences.chatFontSize}
              onChange={(e) => updatePreference('chatFontSize', e.target.value as FontSize)}
              helperText={t('settings.preferences.fontSizeHelper')}
            >
              <option value="small">{t('settings.preferences.small')}</option>
              <option value="medium">{t('settings.preferences.medium')}</option>
              <option value="large">{t('settings.preferences.large')}</option>
              <option value="xlarge">{t('settings.preferences.extraLarge')}</option>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* EN: Accessibility Section / VI: Phần Khả năng truy cập */}
      <Card>
        <CardHeader>
          <CardTitle>{t('settings.preferences.accessibility')}</CardTitle>
          <CardDescription>
            {t('settings.preferences.accessibilityDesc')}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* EN: High contrast mode toggle / VI: Toggle chế độ tương phản cao */}
          <div className="flex items-center justify-between">
            <div className="flex-1">
              <label
                htmlFor="accessibility-high-contrast"
                className="text-sm font-medium text-text-primary cursor-pointer"
              >
                {t('settings.preferences.highContrast')}
              </label>
              <p className="mt-1 text-sm text-text-tertiary">
                {t('settings.preferences.highContrastDesc')}
              </p>
            </div>
            <Switch
              id="accessibility-high-contrast"
              checked={preferences.accessibilityHighContrast}
              onCheckedChange={(checked) => updatePreference('accessibilityHighContrast', checked)}
            />
          </div>

          {/* EN: Screen reader optimizations toggle / VI: Toggle tối ưu screen reader */}
          <div className="flex items-center justify-between">
            <div className="flex-1">
              <label
                htmlFor="accessibility-screen-reader"
                className="text-sm font-medium text-[#FAFAFA] cursor-pointer"
              >
                {t('settings.preferences.screenReader')}
              </label>
              <p className="mt-1 text-sm text-[#A0A0A0]">
                {t('settings.preferences.screenReaderDesc')}
              </p>
            </div>
            <Switch
              id="accessibility-screen-reader"
              checked={preferences.accessibilityScreenReader}
              onCheckedChange={(checked) => updatePreference('accessibilityScreenReader', checked)}
            />
          </div>
        </CardContent>
      </Card>

      {/* EN: Save button / VI: Nút lưu */}
      <div className="flex items-center justify-end gap-4">
        {saveSuccess && (
          <p className="text-sm text-accent-success flex items-center gap-2">
            <svg
              className="h-4 w-4"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              aria-hidden="true"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M5 13l4 4L19 7"
              />
            </svg>
            {t('settings.preferences.preferencesSaved')}
          </p>
        )}
        <Button
          variant="primary"
          onClick={handleSave}
          isLoading={isSaving}
          isDisabled={isSaving}
        >
          {t('settings.preferences.savePreferences')}
        </Button>
      </div>
    </div>
  );
}
