import { useEffect, useState } from 'react';
import type { TrainingRecord } from '../engine/quiz';
import type { AISystem, CompanyProfile, ObligationStatus } from '../engine/types';
import { useI18n } from '../i18n/context';
import { LOCALES } from '../i18n/types';
import { fmt } from '../i18n/ui';
import { loadProfile, loadSystems, loadTraining, saveProfile, saveSystems, saveTraining } from '../store/storage';
import { ChecklistView } from './ChecklistView';
import { Dashboard } from './Dashboard';
import { DisclaimerGate } from './DisclaimerGate';
import { QuizView } from './QuizView';
import { SettingsView } from './SettingsView';
import { SystemDetail } from './SystemDetail';
import { TemplatesView } from './TemplatesView';
import { Wizard } from './Wizard';

type View =
  | { readonly kind: 'dashboard' }
  | { readonly kind: 'tasks' }
  | { readonly kind: 'templates' }
  | { readonly kind: 'quiz' }
  | { readonly kind: 'wizard'; readonly systemId: string | null }
  | { readonly kind: 'detail'; readonly systemId: string }
  | { readonly kind: 'settings' };

/** App-Shell: Navigation, State-Verwaltung und Persistenz. */
export function App(): JSX.Element {
  const { t, locale, setLocale } = useI18n();
  const [systems, setSystems] = useState<readonly AISystem[]>(() => loadSystems());
  const [profile, setProfile] = useState<CompanyProfile>(() => loadProfile());
  const [training, setTraining] = useState<readonly TrainingRecord[]>(() => loadTraining());
  const [view, setView] = useState<View>({ kind: 'dashboard' });

  useEffect(() => {
    saveSystems(systems);
  }, [systems]);

  useEffect(() => {
    saveProfile(profile);
  }, [profile]);

  useEffect(() => {
    saveTraining(training);
  }, [training]);

  const findSystem = (id: string): AISystem | undefined => systems.find((s) => s.id === id);

  const upsert = (system: AISystem): void => {
    setSystems((prev) => {
      const exists = prev.some((s) => s.id === system.id);
      return exists ? prev.map((s) => (s.id === system.id ? system : s)) : [...prev, system];
    });
  };

  const remove = (id: string): void => {
    setSystems((prev) => prev.filter((s) => s.id !== id));
    setView({ kind: 'dashboard' });
  };

  const setObligationStatus = (
    systemId: string,
    obligationId: string,
    status: ObligationStatus,
  ): void => {
    const system = findSystem(systemId);
    if (!system) return;
    upsert({
      ...system,
      updatedAt: new Date().toISOString(),
      obligationStatus: { ...system.obligationStatus, [obligationId]: status },
    });
  };

  return (
    <div className="layout">
      <DisclaimerGate />
      <aside className="sidebar">
        <div className="brand">
          AI-Act-Kompass
          <small>{t.brandTag}</small>
        </div>
        <nav>
          <button
            className={view.kind === 'dashboard' ? 'active' : ''}
            onClick={() => setView({ kind: 'dashboard' })}
          >
            {t.navDashboard}
          </button>
          <button
            className={view.kind === 'tasks' ? 'active' : ''}
            onClick={() => setView({ kind: 'tasks' })}
          >
            {t.navTasks}
          </button>
          <button
            className={view.kind === 'wizard' ? 'active' : ''}
            onClick={() => setView({ kind: 'wizard', systemId: null })}
          >
            {t.navNew}
          </button>
          <button
            className={view.kind === 'templates' ? 'active' : ''}
            onClick={() => setView({ kind: 'templates' })}
          >
            {t.navTemplates}
          </button>
          <button
            className={view.kind === 'quiz' ? 'active' : ''}
            onClick={() => setView({ kind: 'quiz' })}
          >
            {t.navQuiz}
          </button>
          <button
            className={view.kind === 'settings' ? 'active' : ''}
            onClick={() => setView({ kind: 'settings' })}
          >
            {t.navSettings}
          </button>
        </nav>
        <div className="lang-switch">
          {LOCALES.map((l) => (
            <button
              key={l}
              className={l === locale ? 'active' : ''}
              onClick={() => setLocale(l)}
              aria-label={`Sprache ${l}`}
            >
              {l.toUpperCase()}
            </button>
          ))}
        </div>
        <div className="foot">
          {t.footPrivacy}
          <br />
          {t.footLocal}
          <br />
          <br />
          {t.footNoAdvice}
        </div>
      </aside>

      <main className="main">
        {view.kind === 'dashboard' && (
          <Dashboard
            systems={systems}
            profile={profile}
            onOpen={(id) => setView({ kind: 'detail', systemId: id })}
            onNew={() => setView({ kind: 'wizard', systemId: null })}
          />
        )}

        {view.kind === 'tasks' && (
          <ChecklistView
            systems={systems}
            profile={profile}
            onToggle={(systemId, obligationId, done) =>
              setObligationStatus(systemId, obligationId, done ? 'done' : 'open')
            }
            onOpenSystem={(id) => setView({ kind: 'detail', systemId: id })}
          />
        )}

        {view.kind === 'templates' && <TemplatesView systems={systems} profile={profile} />}

        {view.kind === 'quiz' && (
          <QuizView
            profile={profile}
            records={training}
            onRecord={(record) => setTraining((prev) => [record, ...prev])}
          />
        )}

        {view.kind === 'wizard' && (
          <Wizard
            existing={view.systemId ? (findSystem(view.systemId) ?? null) : null}
            onSave={(system) => {
              upsert(system);
              setView({ kind: 'detail', systemId: system.id });
            }}
            onCancel={() => setView({ kind: 'dashboard' })}
          />
        )}

        {view.kind === 'detail' &&
          (() => {
            const system = findSystem(view.systemId);
            if (!system) {
              return <div className="empty">{t.systemNotFound}</div>;
            }
            return (
              <SystemDetail
                system={system}
                profile={profile}
                onUpdate={upsert}
                onReassess={() => setView({ kind: 'wizard', systemId: system.id })}
                onDelete={() => {
                  if (window.confirm(fmt(t.confirmDeleteSystem, { name: system.name }))) {
                    remove(system.id);
                  }
                }}
                onBack={() => setView({ kind: 'dashboard' })}
              />
            );
          })()}

        {view.kind === 'settings' && (
          <SettingsView
            systems={systems}
            profile={profile}
            onProfileChange={setProfile}
            onImport={(imported, importedProfile) => {
              setSystems(imported);
              if (importedProfile) setProfile(importedProfile);
            }}
            onClear={() => {
              setSystems([]);
              setTraining([]);
            }}
          />
        )}
      </main>
    </div>
  );
}
