import { useMemo, useState } from 'react';
import { classify } from '../engine/classify';
import type { AISystem, AssessmentAnswers, ContentItem, Role } from '../engine/types';
import { useI18n } from '../i18n/context';
import { fmt } from '../i18n/ui';
import { RiskBadge, ROLE_UI } from './common';

interface WizardProps {
  /** Bestehendes System bei Neubewertung, sonst null. */
  readonly existing: AISystem | null;
  readonly onSave: (system: AISystem) => void;
  readonly onCancel: () => void;
}

interface Draft {
  name: string;
  purpose: string;
  vendor: string;
  owner: string;
  role: Role;
  defCriteria: readonly string[];
  isGPAIModel: boolean;
  prohibitedPractices: readonly string[];
  annexIIICategories: readonly string[];
  art63Exception: boolean;
  involvesProfiling: boolean;
  isAnnexISafetyComponent: boolean;
  transparencyTriggers: readonly string[];
}

function initialDraft(existing: AISystem | null, allDefIds: readonly string[]): Draft {
  if (!existing) {
    return {
      name: '', purpose: '', vendor: '', owner: '',
      role: 'deployer',
      defCriteria: allDefIds,
      isGPAIModel: false,
      prohibitedPractices: [],
      annexIIICategories: [],
      art63Exception: false,
      involvesProfiling: false,
      isAnnexISafetyComponent: false,
      transparencyTriggers: [],
    };
  }
  const a = existing.answers;
  return {
    name: existing.name,
    purpose: existing.purpose,
    vendor: existing.vendor,
    owner: existing.owner,
    role: a.role,
    defCriteria: a.isAISystem ? allDefIds : [],
    isGPAIModel: a.isGPAIModel,
    prohibitedPractices: a.prohibitedPractices,
    annexIIICategories: a.annexIIICategories,
    art63Exception: a.art63Exception,
    involvesProfiling: a.involvesProfiling,
    isAnnexISafetyComponent: a.isAnnexISafetyComponent,
    transparencyTriggers: a.transparencyTriggers,
  };
}

function toggle(list: readonly string[], id: string): readonly string[] {
  return list.includes(id) ? list.filter((x) => x !== id) : [...list, id];
}

function CheckList({
  items,
  selected,
  onToggle,
}: {
  readonly items: readonly ContentItem[];
  readonly selected: readonly string[];
  readonly onToggle: (id: string) => void;
}): JSX.Element {
  return (
    <div>
      {items.map((item) => (
        <label key={item.id} className="check">
          <input
            type="checkbox"
            checked={selected.includes(item.id)}
            onChange={() => onToggle(item.id)}
          />
          <span>
            {item.label}
            <span className="ref">
              {item.legalRef}
              {item.hint ? ` — ${item.hint}` : ''}
            </span>
          </span>
        </label>
      ))}
    </div>
  );
}

/** Mehrstufiger Bewertungs-Wizard: erfasst ein KI-System und klassifiziert es. */
export function Wizard({ existing, onSave, onCancel }: WizardProps): JSX.Element {
  const { t, locale, pack } = useI18n();
  const steps = [t.stepBasics, t.stepDefinition, t.stepProhibited, t.stepHighRisk, t.stepTransparency, t.stepResult];
  const allDefIds = useMemo(() => pack.aiDefinitionCriteria.map((c) => c.id), [pack]);

  const [step, setStep] = useState(0);
  const [draft, setDraft] = useState<Draft>(() => initialDraft(existing, allDefIds));

  const isAISystem = draft.defCriteria.length === allDefIds.length;

  const answers: AssessmentAnswers = useMemo(
    () => ({
      isAISystem,
      role: draft.role,
      isGPAIModel: draft.isGPAIModel,
      prohibitedPractices: draft.prohibitedPractices,
      annexIIICategories: draft.annexIIICategories,
      art63Exception: draft.art63Exception,
      involvesProfiling: draft.involvesProfiling,
      isAnnexISafetyComponent: draft.isAnnexISafetyComponent,
      transparencyTriggers: draft.transparencyTriggers,
    }),
    [draft, isAISystem],
  );

  const classification = useMemo(() => classify(answers, pack, locale), [answers, pack, locale]);

  const canNext = step !== 0 || draft.name.trim().length > 0;

  const save = (): void => {
    const now = new Date().toISOString();
    onSave({
      id: existing?.id ?? crypto.randomUUID(),
      name: draft.name.trim(),
      purpose: draft.purpose.trim(),
      vendor: draft.vendor.trim(),
      owner: draft.owner.trim(),
      createdAt: existing?.createdAt ?? now,
      updatedAt: now,
      answers,
      classification,
      obligationStatus: existing?.obligationStatus ?? {},
    });
  };

  return (
    <div>
      <h1>{existing ? fmt(t.wizardTitleRe, { name: existing.name }) : t.wizardTitleNew}</h1>
      <p className="sub">{t.wizardSub}</p>

      <div className="wizard-steps">
        {steps.map((label, i) => (
          <span key={label} className={`step ${i === step ? 'current' : i < step ? 'done' : ''}`}>
            {i + 1}. {label}
          </span>
        ))}
      </div>

      <div className="panel">
        {step === 0 && (
          <>
            <label className="field">
              <span>{t.fieldName}</span>
              <input
                type="text"
                value={draft.name}
                placeholder={t.fieldNamePh}
                onChange={(e) => setDraft({ ...draft, name: e.target.value })}
              />
            </label>
            <label className="field">
              <span>{t.fieldPurpose}</span>
              <textarea
                rows={2}
                value={draft.purpose}
                placeholder={t.fieldPurposePh}
                onChange={(e) => setDraft({ ...draft, purpose: e.target.value })}
              />
            </label>
            <label className="field">
              <span>{t.fieldVendor}</span>
              <input type="text" value={draft.vendor} onChange={(e) => setDraft({ ...draft, vendor: e.target.value })} />
            </label>
            <label className="field">
              <span>{t.fieldOwner}</span>
              <input type="text" value={draft.owner} onChange={(e) => setDraft({ ...draft, owner: e.target.value })} />
            </label>
            <label className="field">
              <span>{t.fieldRole}</span>
              <select value={draft.role} onChange={(e) => setDraft({ ...draft, role: e.target.value as Role })}>
                {(Object.keys(ROLE_UI[locale]) as Role[]).map((r) => (
                  <option key={r} value={r}>
                    {ROLE_UI[locale][r]}
                  </option>
                ))}
              </select>
              <span className="hint">{t.roleHint}</span>
            </label>
          </>
        )}

        {step === 1 && (
          <>
            <h2>{t.defTitle}</h2>
            <p className="hint">{t.defHint}</p>
            <CheckList
              items={pack.aiDefinitionCriteria}
              selected={draft.defCriteria}
              onToggle={(id) => setDraft({ ...draft, defCriteria: toggle(draft.defCriteria, id) })}
            />
            {!isAISystem && <p className="hint">⚠ {t.defWarn}</p>}
          </>
        )}

        {step === 2 && (
          <>
            <h2>{t.prohTitle}</h2>
            <p className="hint">{t.prohHint}</p>
            <CheckList
              items={pack.prohibitedPractices}
              selected={draft.prohibitedPractices}
              onToggle={(id) => setDraft({ ...draft, prohibitedPractices: toggle(draft.prohibitedPractices, id) })}
            />
          </>
        )}

        {step === 3 && (
          <>
            <h2>{t.hrTitle}</h2>
            <label className="check">
              <input
                type="checkbox"
                checked={draft.isAnnexISafetyComponent}
                onChange={(e) => setDraft({ ...draft, isAnnexISafetyComponent: e.target.checked })}
              />
              <span>
                {t.annexILabel}
                <span className="ref">Art. 6 Abs. 1, Annex I</span>
              </span>
            </label>
            <h2>{t.annexIIITitle}</h2>
            <CheckList
              items={pack.annexIIICategories}
              selected={draft.annexIIICategories}
              onToggle={(id) => setDraft({ ...draft, annexIIICategories: toggle(draft.annexIIICategories, id) })}
            />
            {draft.annexIIICategories.length > 0 && (
              <>
                <h2>{t.exceptionTitle}</h2>
                <label className="check">
                  <input
                    type="checkbox"
                    checked={draft.involvesProfiling}
                    onChange={(e) => setDraft({ ...draft, involvesProfiling: e.target.checked })}
                  />
                  <span>
                    {t.profilingLabel}
                    <span className="ref">{t.profilingRef}</span>
                  </span>
                </label>
                <label className="check">
                  <input
                    type="checkbox"
                    checked={draft.art63Exception}
                    onChange={(e) => setDraft({ ...draft, art63Exception: e.target.checked })}
                  />
                  <span>
                    {t.art63Label}
                    <span className="ref">{t.art63Ref}</span>
                  </span>
                </label>
              </>
            )}
          </>
        )}

        {step === 4 && (
          <>
            <h2>{t.trTitle}</h2>
            <CheckList
              items={pack.transparencyTriggers}
              selected={draft.transparencyTriggers}
              onToggle={(id) => setDraft({ ...draft, transparencyTriggers: toggle(draft.transparencyTriggers, id) })}
            />
            <h2>{t.gpaiTitle}</h2>
            <label className="check">
              <input
                type="checkbox"
                checked={draft.isGPAIModel}
                onChange={(e) => setDraft({ ...draft, isGPAIModel: e.target.checked })}
              />
              <span>
                {t.gpaiLabel}
                <span className="ref">{t.gpaiRef}</span>
              </span>
            </label>
          </>
        )}

        {step === 5 && (
          <>
            <h2>
              {t.resultTitle} <RiskBadge risk={classification.riskClass} />
            </h2>
            <ul className="reasons">
              {classification.reasons.map((r) => (
                <li key={r}>{r}</li>
              ))}
            </ul>
            {classification.gpaiObligations && <p className="hint">{t.resultGpai}</p>}
            {classification.riskClass === 'prohibited' && <p className="hint">⚠ {t.resultProhibited}</p>}
            <p className="disclaimer">{t.resultDisclaimer}</p>
          </>
        )}
      </div>

      <div className="wizard-nav">
        <div>
          <button className="ghost" onClick={onCancel}>
            {t.btnCancel}
          </button>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          {step > 0 && (
            <button className="ghost" onClick={() => setStep(step - 1)}>
              {t.btnBack}
            </button>
          )}
          {step < steps.length - 1 && (
            <button
              className="primary"
              disabled={!canNext}
              onClick={() => setStep(isAISystem || step === 0 ? step + 1 : steps.length - 1)}
            >
              {t.btnNext}
            </button>
          )}
          {step === steps.length - 1 && (
            <button className="primary" disabled={draft.name.trim().length === 0} onClick={save}>
              {t.btnSave}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
