import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';

import {
  listSounds,
  subscribeSoundboardChanges,
  type SoundboardEntry,
} from '../lib/soundboardStorage';
import { SoundboardManagerDialog } from './SoundboardManagerDialog';
import { ArrowRightIcon } from './icons';

// Entry point into the soundboard manager from the settings page. Shows a
// tiny summary (count, category count) and opens the big dialog on click.
export function SoundboardSettings() {
  const { t } = useTranslation(['app']);
  const [open, setOpen] = useState(false);
  const [entries, setEntries] = useState<SoundboardEntry[]>([]);

  useEffect(() => {
    let cancelled = false;
    const refresh = async () => {
      try {
        const all = await listSounds();
        if (!cancelled) setEntries(all);
      } catch (err: unknown) {
        console.warn('listSounds failed', err);
      }
    };
    void refresh();
    const unsub = subscribeSoundboardChanges(() => {
      void refresh();
    });
    return () => {
      cancelled = true;
      unsub();
    };
  }, []);

  const categoryCount = new Set(entries.map((e) => e.category ?? '__uncat')).size;
  const withHotkey = entries.filter((e) => e.hotkey !== null).length;

  return (
    <>
      <div className="flex items-center justify-between gap-4">
        <div className="min-w-0 flex-1">
          <p className="text-sm font-medium text-fg">
            {t('app:soundboard.summary_title', { defaultValue: 'Deine Sounds' })}
          </p>
          <p className="mt-1 text-xs text-fg-muted">
            {entries.length === 0
              ? t('app:soundboard.summary_empty', {
                  defaultValue: 'Noch keine Sounds vorhanden.',
                })
              : t('app:soundboard.summary_counts', {
                  defaultValue:
                    '{{sounds}} Sounds · {{categories}} Kategorien · {{hotkeys}} mit Hotkey',
                  sounds: entries.length,
                  categories: categoryCount,
                  hotkeys: withHotkey,
                })}
          </p>
        </div>
        <button
          type="button"
          onClick={() => setOpen(true)}
          className="inline-flex shrink-0 cursor-pointer items-center gap-1.5 rounded-lg bg-accent px-3 py-1.5 text-xs font-semibold text-accent-fg transition hover:brightness-110"
        >
          <span>
            {t('app:soundboard.manage', { defaultValue: 'Verwalten' })}
          </span>
          <ArrowRightIcon className="h-3.5 w-3.5" />
        </button>
      </div>
      <p className="text-[11px] text-fg-muted">
        {t('app:soundboard.settings_hint', {
          defaultValue:
            'Hotkeys sind optional. Sounds lassen sich auch während eines Anrufs direkt im UI abspielen.',
        })}
      </p>
      <SoundboardManagerDialog open={open} onClose={() => setOpen(false)} />
    </>
  );
}
