import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { fetchMyOrgs, Visibility } from '../../api';
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { HelpText } from './HelpText';
import { SUPPORTED_LANGUAGES, LANGUAGE_STORAGE_KEY, type SupportedLanguage } from '../../i18n';

const LANGUAGE_LABELS: Record<SupportedLanguage, string> = { en: 'English', ja: '日本語' };

export function PreferencesForm({ user }: { user: { defaultVisibility: Visibility; defaultVisibilityOrgId: string | null } }) {
  const { t, i18n } = useTranslation('settings');
  const { data: orgs = [] } = useQuery({ queryKey: ['my-orgs'], queryFn: fetchMyOrgs });
  const qc = useQueryClient();
  const [vis, setVis] = useState<Visibility>(user.defaultVisibility);
  const [orgId, setOrgId] = useState<string | null>(user.defaultVisibilityOrgId);
  useEffect(() => { setVis(user.defaultVisibility); setOrgId(user.defaultVisibilityOrgId); }, [user]);

  const changeLanguage = (lng: string) => {
    void i18n.changeLanguage(lng);
    try { localStorage.setItem(LANGUAGE_STORAGE_KEY, lng); } catch { /* storage may be unavailable */ }
  };

  const save = useMutation({
    mutationFn: async () => {
      const res = await fetch('/api/users/me/preferences', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ defaultVisibility: vis, defaultVisibilityOrgId: vis === 'org' ? orgId : null }),
      });
      if (!res.ok) throw new Error(await res.text());
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: ['auth', 'me'] }),
  });

  return (
    <div className="space-y-4">
      <section>
        <h3 className="text-sm font-bold text-slate-900">{t('preferences.language.title')}</h3>
        <div className="mt-2 flex gap-3 text-[13px]">
          {SUPPORTED_LANGUAGES.map(lng => (
            <label key={lng}>
              <input type="radio" name="ui-language" checked={i18n.resolvedLanguage === lng} onChange={() => changeLanguage(lng)} /> {LANGUAGE_LABELS[lng]}
            </label>
          ))}
        </div>
        <HelpText>{t('preferences.language.help')}</HelpText>
      </section>
      <section>
        <h3 className="text-sm font-bold text-slate-900">{t('preferences.visibility.title')}</h3>
        <div className="mt-2 flex gap-3 text-[13px]">
          <label><input type="radio" checked={vis === 'private'} onChange={() => setVis('private')} /> 🔒 {t('preferences.visibility.private')}</label>
          <label><input type="radio" checked={vis === 'org'} onChange={() => setVis('org')} disabled={orgs.length === 0} /> 🏢 {t('preferences.visibility.org')}</label>
          <label><input type="radio" checked={vis === 'public'} onChange={() => setVis('public')} /> 🌐 {t('preferences.visibility.public')}</label>
        </div>
        <HelpText>{t('preferences.visibility.help')}</HelpText>
        {vis === 'org' && (
          <select value={orgId ?? ''} onChange={e => setOrgId(e.target.value)} className="mt-2 px-2 py-1 border rounded text-[13px]">
            {orgs.map(o => <option key={o.orgId} value={o.orgId}>{o.orgName}</option>)}
          </select>
        )}
      </section>
      <section>
        <h3 className="text-sm font-bold text-slate-900">{t('preferences.orgs.title')}</h3>
        <ul className="mt-2 text-[13px] text-slate-700 list-disc pl-5">
          {orgs.map(o => <li key={o.orgId}>{o.orgName}</li>)}
          {orgs.length === 0 && <li className="text-slate-400">{t('preferences.orgs.none')}</li>}
        </ul>
        <p className="mt-2 text-2xs text-slate-500">{t('preferences.orgs.refreshHint')}</p>
      </section>
      <button
        onClick={() => save.mutate()}
        disabled={save.isPending}
        className="px-3 py-1.5 rounded bg-accent text-accent-fg text-[13px]"
      >
        {save.isPending ? t('preferences.saving') : t('preferences.save')}
      </button>
      {save.isError && <div className="text-red-600 text-xs">{String(save.error)}</div>}
    </div>
  );
}
