import { useState } from 'react';
import { useNavigate } from '@tanstack/react-router';
import { useUiStore, type Theme } from '@/stores/uiStore';
import { exportBackup, restoreBackup, clearAllData, BackupError } from '@/lib/io/backup';
import { pickTextFile } from '@/lib/io/file';
import { seedSampleCampaign } from '@/lib/sample';
import { AssistantSettings } from './AssistantSettings';
import { Page, PageHeader } from '@/components/ui/Page';
import { Button } from '@/components/ui/Button';
import { Modal } from '@/components/ui/Modal';
import { cn } from '@/lib/cn';

export function SettingsPage() {
  const theme = useUiStore((s) => s.theme);
  const setTheme = useUiStore((s) => s.setTheme);
  const setActiveCampaign = useUiStore((s) => s.setActiveCampaign);
  const navigate = useNavigate();
  const [msg, setMsg] = useState<string | null>(null);
  const [confirmRestore, setConfirmRestore] = useState<string | null>(null);
  const [confirmClear, setConfirmClear] = useState(false);

  const doImport = async () => {
    const text = await pickTextFile();
    if (text) setConfirmRestore(text);
  };
  const runRestore = async () => {
    if (!confirmRestore) return;
    try {
      await restoreBackup(confirmRestore);
      setMsg('Backup restored.');
    } catch (e) {
      setMsg(e instanceof BackupError ? e.message : 'Restore failed.');
    }
    setConfirmRestore(null);
  };
  const loadSample = async () => {
    const id = await seedSampleCampaign();
    setActiveCampaign(id);
    void navigate({ to: '/dashboard' });
  };

  return (
    <Page>
      <PageHeader title="Settings" subtitle="Appearance, backups, and data." />

      <section className="mb-8">
        <h2 className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted">Appearance</h2>
        <div className="flex gap-2">
          {(['dark', 'light'] as Theme[]).map((t) => (
            <Button key={t} variant={theme === t ? 'primary' : 'secondary'} onClick={() => setTheme(t)} className="capitalize">
              {t}
            </Button>
          ))}
        </div>
      </section>

      <section className="mb-8">
        <h2 className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted">Data</h2>
        <div className="flex flex-wrap gap-2">
          <Button variant="secondary" onClick={() => void exportBackup()}>Export backup</Button>
          <Button variant="secondary" onClick={doImport}>Import backup…</Button>
          <Button variant="secondary" onClick={loadSample}>Load sample campaign</Button>
        </div>
        <p className="mt-2 text-xs text-muted">Backups include every campaign and all of its data, as a single JSON file.</p>
        {msg && <p className={cn('mt-2 text-sm', msg.includes('fail') || msg.includes('not') ? 'text-danger' : 'text-success')}>{msg}</p>}
      </section>

      <AssistantSettings />

      <section className="rounded-lg border border-danger/40 bg-danger/5 p-4">
        <h2 className="mb-1 text-sm font-semibold text-danger">Danger zone</h2>
        <p className="mb-3 text-sm text-muted">Permanently delete all campaigns and data on this device.</p>
        <Button variant="danger" onClick={() => setConfirmClear(true)}>Clear all data</Button>
      </section>

      <Modal
        open={!!confirmRestore}
        onClose={() => setConfirmRestore(null)}
        title="Restore backup?"
        footer={
          <>
            <Button variant="ghost" onClick={() => setConfirmRestore(null)}>Cancel</Button>
            <Button variant="danger" onClick={runRestore}>Replace all data</Button>
          </>
        }
      >
        <p className="text-sm text-muted">Restoring <strong className="text-ink">replaces all current data</strong> with the backup. Export first if unsure.</p>
      </Modal>

      <Modal
        open={confirmClear}
        onClose={() => setConfirmClear(false)}
        title="Clear all data?"
        footer={
          <>
            <Button variant="ghost" onClick={() => setConfirmClear(false)}>Cancel</Button>
            <Button variant="danger" onClick={async () => { await clearAllData(); setActiveCampaign(null); setConfirmClear(false); setMsg('All data cleared.'); }}>Delete everything</Button>
          </>
        }
      >
        <p className="text-sm text-muted">This deletes every campaign, character, encounter, note, map, and homebrew entry. This cannot be undone.</p>
      </Modal>
    </Page>
  );
}
