'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { apiClient } from '@/infrastructure/api/api-client';
import { queryKeys } from '@/infrastructure/api/query-keys';
import { format } from 'date-fns';
import { useLocaleStore, type SupportedLocale } from '@/stores/zustand/locale-store';

/* ------------------------------------------------------------------ */
/*  Types                                                              */
/* ------------------------------------------------------------------ */

interface PlatformSettings {
  platformName: string;
  defaultTimezone: string;
  defaultLanguage: string;
  autoApproveThreshold: number;
}

interface NotificationSettings {
  emailEnabled: boolean;
  smsEnabled: boolean;
  pushEnabled: boolean;
  defaultEscalationPolicy: string;
}

interface ApiKey {
  id: string;
  name: string;
  key: string;
  createdAt: string;
  lastUsedAt: string | null;
}

interface ThemeSettings {
  mode: 'light' | 'dark';
  primaryColor: string;
}

interface AccountInfo {
  displayName: string;
  email: string;
}

/* ------------------------------------------------------------------ */
/*  Constants                                                          */
/* ------------------------------------------------------------------ */

type SectionId = 'general' | 'notifications' | 'apikeys' | 'theme' | 'account' | 'voice';

const SECTION_IDS: SectionId[] = ['general', 'notifications', 'apikeys', 'theme', 'account', 'voice'];

const TIMEZONES = [
  'UTC', 'America/New_York', 'America/Chicago', 'America/Denver',
  'America/Los_Angeles', 'Europe/London', 'Europe/Berlin', 'Europe/Paris',
  'Asia/Tokyo', 'Asia/Shanghai', 'Asia/Seoul', 'Asia/Singapore',
  'Australia/Sydney',
];

const UI_LANGUAGES: { value: SupportedLocale; labelKey: string }[] = [
  { value: 'en', labelKey: 'languages.en' },
  { value: 'zh', labelKey: 'languages.zh' },
];

const PLATFORM_LANGUAGES = ['en', 'ko', 'ja', 'zh', 'de', 'fr'];

const ESCALATION_POLICIES = ['immediate', 'after-5-min', 'after-15-min', 'after-30-min', 'manual'];

const COLOR_PRESETS = [
  '#3b82f6', '#6366f1', '#8b5cf6', '#ec4899',
  '#ef4444', '#f97316', '#10b981', '#14b8a6',
];

/* ------------------------------------------------------------------ */
/*  Page                                                               */
/* ------------------------------------------------------------------ */

export default function SettingsPage() {
  const { t } = useTranslation('settings');
  const [activeSection, setActiveSection] = useState<SectionId>('general');

  return (
    <div>
      <h1 className="text-2xl font-bold mb-1">{t('title')}</h1>
      <p className="text-sm text-muted-foreground mb-6">
        {t('subtitle')}
      </p>

      <div className="flex gap-6">
        {/* ---- Section Nav ---- */}
        <nav className="w-48 shrink-0">
          <ul className="space-y-1">
            {SECTION_IDS.map((id) => (
              <li key={id}>
                <button
                  onClick={() => setActiveSection(id)}
                  className={`w-full text-left px-3 py-2 rounded-md text-sm font-medium transition-colors ${
                    activeSection === id
                      ? 'bg-primary text-primary-foreground'
                      : 'hover:bg-muted text-muted-foreground'
                  }`}
                >
                  {t(`sections.${id}`)}
                </button>
              </li>
            ))}
          </ul>
        </nav>

        {/* ---- Section Content ---- */}
        <div className="flex-1 min-w-0">
          {activeSection === 'general' && <GeneralSection />}
          {activeSection === 'notifications' && <NotificationsSection />}
          {activeSection === 'apikeys' && <ApiKeysSection />}
          {activeSection === 'theme' && <ThemeSection />}
          {activeSection === 'account' && <AccountSection />}
          {activeSection === 'voice' && <VoiceSection />}
        </div>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  General Section                                                    */
/* ------------------------------------------------------------------ */

function GeneralSection() {
  const { t } = useTranslation('settings');
  const { t: tc } = useTranslation('common');
  const queryClient = useQueryClient();
  const { locale, setLocale } = useLocaleStore();

  const { data, isLoading } = useQuery<PlatformSettings>({
    queryKey: queryKeys.settings.general(),
    queryFn: () => apiClient<PlatformSettings>('/api/v1/admin/settings/general'),
  });

  const [form, setForm] = useState<PlatformSettings>({
    platformName: '',
    defaultTimezone: 'UTC',
    defaultLanguage: 'en',
    autoApproveThreshold: 1,
  });
  const [initialized, setInitialized] = useState(false);

  if (data && !initialized) {
    setForm(data);
    setInitialized(true);
  }

  const mutation = useMutation({
    mutationFn: (body: PlatformSettings) =>
      apiClient('/api/v1/admin/settings/general', { method: 'PUT', body }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.settings.all }),
  });

  return (
    <div className="bg-card border rounded-lg p-6">
      <h2 className="text-lg font-semibold mb-4">{t('general.title')}</h2>

      {isLoading ? (
        <p className="text-muted-foreground text-sm">{tc('loading')}</p>
      ) : (
        <div className="space-y-4 max-w-lg">
          {/* UI Language selector */}
          <div>
            <label className="block text-sm font-medium mb-1">{t('general.uiLanguage')}</label>
            <select
              className="w-full border rounded-md px-3 py-2 bg-background text-sm"
              value={locale}
              onChange={(e) => setLocale(e.target.value as SupportedLocale)}
            >
              {UI_LANGUAGES.map((l) => (
                <option key={l.value} value={l.value}>{t(l.labelKey)}</option>
              ))}
            </select>
            <p className="text-xs text-muted-foreground mt-1">
              {t('general.uiLanguageHint')}
            </p>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">{t('general.platformName')}</label>
            <input
              className="w-full border rounded-md px-3 py-2 bg-background text-sm"
              value={form.platformName}
              onChange={(e) => setForm({ ...form, platformName: e.target.value })}
              placeholder={t('general.platformNamePlaceholder')}
            />
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">{t('general.defaultTimezone')}</label>
            <select
              className="w-full border rounded-md px-3 py-2 bg-background text-sm"
              value={form.defaultTimezone}
              onChange={(e) => setForm({ ...form, defaultTimezone: e.target.value })}
            >
              {TIMEZONES.map((tz) => (
                <option key={tz} value={tz}>{tz}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">{t('general.defaultLanguage')}</label>
            <select
              className="w-full border rounded-md px-3 py-2 bg-background text-sm"
              value={form.defaultLanguage}
              onChange={(e) => setForm({ ...form, defaultLanguage: e.target.value })}
            >
              {PLATFORM_LANGUAGES.map((code) => (
                <option key={code} value={code}>{t(`languages.${code}`)}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">
              {t('general.autoApproveThreshold')}
            </label>
            <input
              type="number"
              min={0}
              max={3}
              className="w-full border rounded-md px-3 py-2 bg-background text-sm"
              value={form.autoApproveThreshold}
              onChange={(e) =>
                setForm({ ...form, autoApproveThreshold: Math.min(3, Math.max(0, Number(e.target.value))) })
              }
            />
            <p className="text-xs text-muted-foreground mt-1">
              {t('general.autoApproveHint')}
            </p>
          </div>

          <button
            onClick={() => mutation.mutate(form)}
            disabled={mutation.isPending}
            className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50"
          >
            {mutation.isPending ? tc('saving') : tc('save')}
          </button>

          {mutation.isError && (
            <p className="text-sm text-red-500">{(mutation.error as Error).message}</p>
          )}
          {mutation.isSuccess && (
            <p className="text-sm text-green-600">{t('general.saved')}</p>
          )}
        </div>
      )}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Notifications Section                                              */
/* ------------------------------------------------------------------ */

function NotificationsSection() {
  const { t } = useTranslation('settings');
  const { t: tc } = useTranslation('common');
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery<NotificationSettings>({
    queryKey: queryKeys.settings.notifications(),
    queryFn: () => apiClient<NotificationSettings>('/api/v1/admin/settings/notifications'),
  });

  const [form, setForm] = useState<NotificationSettings>({
    emailEnabled: true,
    smsEnabled: false,
    pushEnabled: false,
    defaultEscalationPolicy: 'immediate',
  });
  const [initialized, setInitialized] = useState(false);

  if (data && !initialized) {
    setForm(data);
    setInitialized(true);
  }

  const mutation = useMutation({
    mutationFn: (body: NotificationSettings) =>
      apiClient('/api/v1/admin/settings/notifications', { method: 'PUT', body }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.settings.all }),
  });

  function Toggle({ checked, onChange, label }: { checked: boolean; onChange: (v: boolean) => void; label: string }) {
    return (
      <label className="flex items-center justify-between py-2">
        <span className="text-sm font-medium">{label}</span>
        <button
          type="button"
          role="switch"
          aria-checked={checked}
          onClick={() => onChange(!checked)}
          className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
            checked ? 'bg-primary' : 'bg-gray-300 dark:bg-gray-600'
          }`}
        >
          <span
            className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
              checked ? 'translate-x-6' : 'translate-x-1'
            }`}
          />
        </button>
      </label>
    );
  }

  return (
    <div className="bg-card border rounded-lg p-6">
      <h2 className="text-lg font-semibold mb-4">{t('notifications.title')}</h2>

      {isLoading ? (
        <p className="text-muted-foreground text-sm">{tc('loading')}</p>
      ) : (
        <div className="space-y-2 max-w-lg">
          <Toggle
            label={t('notifications.email')}
            checked={form.emailEnabled}
            onChange={(v) => setForm({ ...form, emailEnabled: v })}
          />
          <Toggle
            label={t('notifications.sms')}
            checked={form.smsEnabled}
            onChange={(v) => setForm({ ...form, smsEnabled: v })}
          />
          <Toggle
            label={t('notifications.push')}
            checked={form.pushEnabled}
            onChange={(v) => setForm({ ...form, pushEnabled: v })}
          />

          <div className="pt-4">
            <label className="block text-sm font-medium mb-1">{t('notifications.escalationPolicy')}</label>
            <select
              className="w-full border rounded-md px-3 py-2 bg-background text-sm"
              value={form.defaultEscalationPolicy}
              onChange={(e) => setForm({ ...form, defaultEscalationPolicy: e.target.value })}
            >
              {ESCALATION_POLICIES.map((p) => (
                <option key={p} value={p}>
                  {p.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())}
                </option>
              ))}
            </select>
          </div>

          <div className="pt-4">
            <button
              onClick={() => mutation.mutate(form)}
              disabled={mutation.isPending}
              className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50"
            >
              {mutation.isPending ? tc('saving') : tc('save')}
            </button>
          </div>

          {mutation.isError && (
            <p className="text-sm text-red-500">{(mutation.error as Error).message}</p>
          )}
          {mutation.isSuccess && (
            <p className="text-sm text-green-600">{t('notifications.saved')}</p>
          )}
        </div>
      )}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  API Keys Section                                                   */
/* ------------------------------------------------------------------ */

function ApiKeysSection() {
  const { t } = useTranslation('settings');
  const { t: tc } = useTranslation('common');
  const queryClient = useQueryClient();
  const [newKeyName, setNewKeyName] = useState('');
  const [generatedKey, setGeneratedKey] = useState<string | null>(null);

  const { data: apiKeys = [], isLoading } = useQuery<ApiKey[]>({
    queryKey: queryKeys.settings.apiKeys(),
    queryFn: () => apiClient<ApiKey[]>('/api/v1/admin/settings/api-keys'),
  });

  const invalidate = () =>
    queryClient.invalidateQueries({ queryKey: queryKeys.settings.apiKeys() });

  const createMutation = useMutation({
    mutationFn: (name: string) =>
      apiClient<{ key: string }>('/api/v1/admin/settings/api-keys', {
        method: 'POST',
        body: { name },
      }),
    onSuccess: (data) => {
      setGeneratedKey((data as { key: string }).key);
      setNewKeyName('');
      invalidate();
    },
  });

  const revokeMutation = useMutation({
    mutationFn: (id: string) =>
      apiClient(`/api/v1/admin/settings/api-keys/${id}`, { method: 'DELETE' }),
    onSuccess: invalidate,
  });

  function maskKey(key: string) {
    if (key.length <= 8) return key;
    return key.slice(0, 4) + '****' + key.slice(-4);
  }

  return (
    <div className="bg-card border rounded-lg p-6">
      <h2 className="text-lg font-semibold mb-4">{t('apikeys.title')}</h2>

      {/* Generate new key */}
      <div className="flex gap-2 mb-4 max-w-lg">
        <input
          className="flex-1 border rounded-md px-3 py-2 bg-background text-sm"
          value={newKeyName}
          onChange={(e) => setNewKeyName(e.target.value)}
          placeholder={t('apikeys.namePlaceholder')}
        />
        <button
          disabled={!newKeyName.trim() || createMutation.isPending}
          onClick={() => createMutation.mutate(newKeyName.trim())}
          className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50 whitespace-nowrap"
        >
          {t('apikeys.generate')}
        </button>
      </div>

      {/* Show generated key once */}
      {generatedKey && (
        <div className="mb-4 p-3 bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-800 rounded-md">
          <p className="text-sm font-medium text-green-800 dark:text-green-300 mb-1">
            {t('apikeys.generatedWarning')}
          </p>
          <code className="block text-sm bg-white dark:bg-gray-900 p-2 rounded border font-mono break-all">
            {generatedKey}
          </code>
          <button
            onClick={() => {
              navigator.clipboard.writeText(generatedKey);
            }}
            className="mt-2 px-3 py-1 text-xs border rounded hover:bg-muted"
          >
            {t('apikeys.copyToClipboard')}
          </button>
          <button
            onClick={() => setGeneratedKey(null)}
            className="mt-2 ml-2 px-3 py-1 text-xs border rounded hover:bg-muted"
          >
            {t('apikeys.dismiss')}
          </button>
        </div>
      )}

      {/* Keys table */}
      {isLoading ? (
        <p className="text-muted-foreground text-sm">{tc('loading')}</p>
      ) : (
        <div className="border rounded-lg overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-muted/50">
              <tr className="text-left">
                <th className="px-4 py-3 font-medium">{t('apikeys.headerName')}</th>
                <th className="px-4 py-3 font-medium">{t('apikeys.headerKey')}</th>
                <th className="px-4 py-3 font-medium">{t('apikeys.headerCreated')}</th>
                <th className="px-4 py-3 font-medium">{t('apikeys.headerLastUsed')}</th>
                <th className="px-4 py-3 font-medium text-right">{t('apikeys.headerActions')}</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {apiKeys.map((k) => (
                <tr key={k.id} className="hover:bg-muted/30">
                  <td className="px-4 py-3 font-medium">{k.name}</td>
                  <td className="px-4 py-3 font-mono text-muted-foreground">{maskKey(k.key)}</td>
                  <td className="px-4 py-3 text-muted-foreground">
                    {format(new Date(k.createdAt), 'MMM d, yyyy')}
                  </td>
                  <td className="px-4 py-3 text-muted-foreground">
                    {k.lastUsedAt ? format(new Date(k.lastUsedAt), 'MMM d, yyyy') : tc('never')}
                  </td>
                  <td className="px-4 py-3 text-right">
                    <button
                      onClick={() => revokeMutation.mutate(k.id)}
                      disabled={revokeMutation.isPending}
                      className="px-2 py-1 text-xs bg-red-100 text-red-700 rounded hover:bg-red-200 dark:bg-red-900 dark:text-red-300 disabled:opacity-50"
                    >
                      {t('apikeys.revoke')}
                    </button>
                  </td>
                </tr>
              ))}
              {apiKeys.length === 0 && (
                <tr>
                  <td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
                    {t('apikeys.noKeys')}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      )}

      {createMutation.isError && (
        <p className="text-sm text-red-500 mt-2">{(createMutation.error as Error).message}</p>
      )}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Theme Section                                                      */
/* ------------------------------------------------------------------ */

function ThemeSection() {
  const { t } = useTranslation('settings');
  const { t: tc } = useTranslation('common');
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery<ThemeSettings>({
    queryKey: queryKeys.settings.theme(),
    queryFn: () => apiClient<ThemeSettings>('/api/v1/admin/settings/theme'),
  });

  const [mode, setMode] = useState<'light' | 'dark'>('light');
  const [primaryColor, setPrimaryColor] = useState('#3b82f6');
  const [initialized, setInitialized] = useState(false);

  if (data && !initialized) {
    setMode(data.mode);
    setPrimaryColor(data.primaryColor);
    setInitialized(true);
  }

  const mutation = useMutation({
    mutationFn: (body: ThemeSettings) =>
      apiClient('/api/v1/admin/settings/theme', { method: 'PUT', body }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.settings.all }),
  });

  return (
    <div className="bg-card border rounded-lg p-6">
      <h2 className="text-lg font-semibold mb-4">{t('theme.title')}</h2>

      {isLoading ? (
        <p className="text-muted-foreground text-sm">{tc('loading')}</p>
      ) : (
        <div className="space-y-6 max-w-lg">
          {/* Mode toggle */}
          <div>
            <label className="block text-sm font-medium mb-2">{t('theme.appearance')}</label>
            <div className="flex gap-2">
              {(['light', 'dark'] as const).map((m) => (
                <button
                  key={m}
                  onClick={() => setMode(m)}
                  className={`px-4 py-2 text-sm rounded-md border font-medium transition-colors ${
                    mode === m
                      ? 'bg-primary text-primary-foreground border-primary'
                      : 'hover:bg-muted'
                  }`}
                >
                  {t(`theme.${m}`)}
                </button>
              ))}
            </div>
          </div>

          {/* Color presets */}
          <div>
            <label className="block text-sm font-medium mb-2">{t('theme.primaryColor')}</label>
            <div className="flex gap-2 flex-wrap">
              {COLOR_PRESETS.map((c) => (
                <button
                  key={c}
                  onClick={() => setPrimaryColor(c)}
                  className={`w-8 h-8 rounded-full border-2 transition-transform ${
                    primaryColor === c ? 'border-foreground scale-110' : 'border-transparent'
                  }`}
                  style={{ backgroundColor: c }}
                  title={c}
                />
              ))}
              <input
                type="color"
                value={primaryColor}
                onChange={(e) => setPrimaryColor(e.target.value)}
                className="w-8 h-8 rounded-full cursor-pointer border-0 p-0"
                title={t('theme.customColor')}
              />
            </div>
            <p className="text-xs text-muted-foreground mt-1">
              {t('theme.selected', { color: primaryColor })}
            </p>
          </div>

          <button
            onClick={() => mutation.mutate({ mode, primaryColor })}
            disabled={mutation.isPending}
            className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50"
          >
            {mutation.isPending ? tc('saving') : t('theme.saveTheme')}
          </button>

          {mutation.isError && (
            <p className="text-sm text-red-500">{(mutation.error as Error).message}</p>
          )}
          {mutation.isSuccess && (
            <p className="text-sm text-green-600">{t('theme.saved')}</p>
          )}
        </div>
      )}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Account Section                                                    */
/* ------------------------------------------------------------------ */

function AccountSection() {
  const { t } = useTranslation('settings');
  const { t: tc } = useTranslation('common');
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery<AccountInfo>({
    queryKey: queryKeys.settings.account(),
    queryFn: () => apiClient<AccountInfo>('/api/v1/admin/settings/account'),
  });

  const [displayName, setDisplayName] = useState('');
  const [email, setEmail] = useState('');
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [initialized, setInitialized] = useState(false);

  if (data && !initialized) {
    setDisplayName(data.displayName);
    setEmail(data.email);
    setInitialized(true);
  }

  const profileMutation = useMutation({
    mutationFn: (body: { displayName: string }) =>
      apiClient('/api/v1/admin/settings/account', { method: 'PUT', body }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.settings.account() }),
  });

  const passwordMutation = useMutation({
    mutationFn: (body: { currentPassword: string; newPassword: string }) =>
      apiClient('/api/v1/admin/settings/account/password', { method: 'PUT', body }),
    onSuccess: () => {
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
    },
  });

  const passwordMismatch = confirmPassword !== '' && newPassword !== confirmPassword;

  return (
    <div className="space-y-6">
      {/* Profile card */}
      <div className="bg-card border rounded-lg p-6">
        <h2 className="text-lg font-semibold mb-4">{t('account.profileTitle')}</h2>

        {isLoading ? (
          <p className="text-muted-foreground text-sm">{tc('loading')}</p>
        ) : (
          <div className="space-y-4 max-w-lg">
            <div>
              <label className="block text-sm font-medium mb-1">{t('account.displayName')}</label>
              <input
                className="w-full border rounded-md px-3 py-2 bg-background text-sm"
                value={displayName}
                onChange={(e) => setDisplayName(e.target.value)}
              />
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">{t('account.email')}</label>
              <input
                className="w-full border rounded-md px-3 py-2 bg-muted text-sm cursor-not-allowed"
                value={email}
                readOnly
              />
              <p className="text-xs text-muted-foreground mt-1">
                {t('account.emailHint')}
              </p>
            </div>

            <button
              onClick={() => profileMutation.mutate({ displayName })}
              disabled={profileMutation.isPending || !displayName.trim()}
              className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50"
            >
              {profileMutation.isPending ? tc('saving') : t('account.saveProfile')}
            </button>

            {profileMutation.isError && (
              <p className="text-sm text-red-500">{(profileMutation.error as Error).message}</p>
            )}
            {profileMutation.isSuccess && (
              <p className="text-sm text-green-600">{t('account.profileSaved')}</p>
            )}
          </div>
        )}
      </div>

      {/* Password card */}
      <div className="bg-card border rounded-lg p-6">
        <h2 className="text-lg font-semibold mb-4">{t('account.changePassword')}</h2>

        <div className="space-y-4 max-w-lg">
          <div>
            <label className="block text-sm font-medium mb-1">{t('account.currentPassword')}</label>
            <input
              type="password"
              className="w-full border rounded-md px-3 py-2 bg-background text-sm"
              value={currentPassword}
              onChange={(e) => setCurrentPassword(e.target.value)}
            />
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">{t('account.newPassword')}</label>
            <input
              type="password"
              className="w-full border rounded-md px-3 py-2 bg-background text-sm"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
            />
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">{t('account.confirmPassword')}</label>
            <input
              type="password"
              className={`w-full border rounded-md px-3 py-2 bg-background text-sm ${
                passwordMismatch ? 'border-red-500' : ''
              }`}
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
            />
            {passwordMismatch && (
              <p className="text-xs text-red-500 mt-1">{tc('passwordsNoMatch')}</p>
            )}
          </div>

          <button
            onClick={() =>
              passwordMutation.mutate({ currentPassword, newPassword })
            }
            disabled={
              passwordMutation.isPending ||
              !currentPassword ||
              !newPassword ||
              newPassword !== confirmPassword
            }
            className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50"
          >
            {passwordMutation.isPending ? t('account.changing') : t('account.changePassword')}
          </button>

          {passwordMutation.isError && (
            <p className="text-sm text-red-500">{(passwordMutation.error as Error).message}</p>
          )}
          {passwordMutation.isSuccess && (
            <p className="text-sm text-green-600">{t('account.passwordChanged')}</p>
          )}
        </div>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Voice Section                                                      */
/* ------------------------------------------------------------------ */

interface VoiceSettings {
  stt_provider: string;
}

const STT_PROVIDERS = [
  { value: 'openai', labelKey: 'voice.providers.openai' },
];

function VoiceSection() {
  const { t } = useTranslation('settings');
  const { t: tc } = useTranslation('common');
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery<VoiceSettings>({
    queryKey: queryKeys.settings.voice(),
    queryFn: () => apiClient<VoiceSettings>('/api/v1/agent/voice-config'),
  });

  const [sttProvider, setSttProvider] = useState('openai');
  const [initialized, setInitialized] = useState(false);

  if (data && !initialized) {
    setSttProvider(data.stt_provider || 'openai');
    setInitialized(true);
  }

  const mutation = useMutation({
    mutationFn: (body: VoiceSettings) =>
      apiClient('/api/v1/agent/voice-config', { method: 'PUT', body }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.settings.all }),
  });

  return (
    <div className="bg-card border rounded-lg p-6">
      <h2 className="text-lg font-semibold mb-4">{t('voice.title')}</h2>

      {isLoading ? (
        <p className="text-muted-foreground text-sm">{tc('loading')}</p>
      ) : (
        <div className="space-y-4 max-w-lg">
          <div>
            <label className="block text-sm font-medium mb-1">
              {t('voice.sttProvider')}
            </label>
            <select
              className="w-full border rounded-md px-3 py-2 bg-background text-sm"
              value={sttProvider}
              onChange={(e) => setSttProvider(e.target.value)}
            >
              {STT_PROVIDERS.map((p) => (
                <option key={p.value} value={p.value}>
                  {t(p.labelKey)}
                </option>
              ))}
            </select>
            <p className="text-xs text-muted-foreground mt-1">
              {t('voice.sttProviderHint')}
            </p>
          </div>

          <button
            onClick={() => mutation.mutate({ stt_provider: sttProvider })}
            disabled={mutation.isPending}
            className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50"
          >
            {mutation.isPending ? tc('saving') : tc('save')}
          </button>

          {mutation.isError && (
            <p className="text-sm text-red-500">{(mutation.error as Error).message}</p>
          )}
          {mutation.isSuccess && (
            <p className="text-sm text-green-600">{t('voice.saved')}</p>
          )}
        </div>
      )}
    </div>
  );
}
