import { useMemo, useState } from 'react';
import {
  answerKeyDoc,
  certificateDoc,
  getQuiz,
  handoutDoc,
  printableTestDoc,
  scoreQuiz,
  trainingLogDoc,
} from '../engine/quiz';
import type { QuizScore, TrainingRecord } from '../engine/quiz';
import { QUIZ_PASS_PCT } from '../engine/quizContent';
import type { CompanyProfile } from '../engine/types';
import { useI18n } from '../i18n/context';
import { fmt } from '../i18n/ui';
import { printDocument } from '../print/print';
import { todayISO, uiDate } from './common';

interface QuizViewProps {
  readonly profile: CompanyProfile;
  readonly records: readonly TrainingRecord[];
  readonly onRecord: (record: TrainingRecord) => void;
}

/**
 * KI-Kompetenztest (Art. 4): einfacher Grundlagentest mit Auswertung,
 * druckbarem Zertifikat und lokalem Schulungsregister als Nachweis.
 */
export function QuizView({ profile, records, onRecord }: QuizViewProps): JSX.Element {
  const { t, locale, pack } = useI18n();
  const today = todayISO();
  const questions = useMemo(() => getQuiz(locale), [locale]);

  const [name, setName] = useState('');
  const [answers, setAnswers] = useState<readonly (number | null)[]>(() =>
    questions.map(() => null),
  );
  const [result, setResult] = useState<QuizScore | null>(null);

  const complete = name.trim() !== '' && answers.every((a) => a !== null);

  const submit = (): void => {
    const score = scoreQuiz(answers);
    setResult(score);
    onRecord({
      id: crypto.randomUUID(),
      name: name.trim(),
      date: today,
      scorePct: score.pct,
      passed: score.passed,
    });
  };

  const reset = (): void => {
    setAnswers(questions.map(() => null));
    setResult(null);
  };

  return (
    <div>
      <h1>{t.navQuiz}</h1>
      <p className="sub">{t.quizSub}</p>

      {result === null ? (
        <>
          <div className="panel">
            <label className="field">
              <span>{t.quizName}</span>
              <input
                type="text"
                value={name}
                placeholder={t.quizNamePh}
                onChange={(e) => setName(e.target.value)}
              />
            </label>
          </div>

          {questions.map((q, qi) => (
            <div key={q.id} className="panel">
              <h2 style={{ marginTop: 0 }}>
                {qi + 1}. {q.question}
              </h2>
              {q.options.map((option, oi) => (
                <label key={oi} className="check">
                  <input
                    type="radio"
                    name={q.id}
                    checked={answers[qi] === oi}
                    onChange={() =>
                      setAnswers(answers.map((a, i) => (i === qi ? oi : a)))
                    }
                  />
                  <span>{option}</span>
                </label>
              ))}
            </div>
          ))}

          <div className="wizard-nav">
            <span className="hint">{!complete ? t.quizAnswerAll : ''}</span>
            <button className="primary" disabled={!complete} onClick={submit}>
              {t.quizSubmit}
            </button>
          </div>
        </>
      ) : (
        <div className="panel">
          <h2 style={{ marginTop: 0 }}>
            <span className={`badge ${result.passed ? 'minimal' : 'high'}`}>
              {result.passed ? t.quizPassed : t.quizFailed}
            </span>
          </h2>
          <p>
            {fmt(t.quizScoreLine, {
              correct: result.correct,
              total: result.total,
              pct: result.pct,
              pass: QUIZ_PASS_PCT,
            })}
          </p>
          <div className="toolbar">
            <button
              className="primary"
              onClick={() =>
                printDocument(
                  `ki-kompetenz-${name.trim()}-${today}`,
                  certificateDoc(name.trim(), result, pack, today, profile, locale),
                  profile,
                )
              }
            >
              {t.quizCert}
            </button>
            <button className="ghost" onClick={reset}>
              {t.quizRetry}
            </button>
          </div>

          <h2>{t.quizWhy}</h2>
          <ul className="reasons">
            {questions.map((q, qi) => (
              <li key={q.id}>
                <strong>
                  {answers[qi] === q.correctIndex ? '✓' : '✗'} {qi + 1}.
                </strong>{' '}
                {q.explanation}
              </li>
            ))}
          </ul>
        </div>
      )}

      <div className="panel">
        <h2 style={{ marginTop: 0 }}>{t.quizDocsTitle}</h2>
        <div className="toolbar" style={{ marginBottom: 0 }}>
          <button
            className="ghost"
            onClick={() =>
              printDocument(`ki-test-papier-${today}`, printableTestDoc(pack, today, profile, locale), profile)
            }
          >
            {t.quizPrintTest}
          </button>
          <button
            className="ghost"
            onClick={() =>
              printDocument(`ki-test-loesungen-${today}`, answerKeyDoc(pack, today, profile, locale), profile)
            }
          >
            {t.quizPrintKey}
          </button>
          <button
            className="ghost"
            onClick={() =>
              printDocument(`ki-schulungshandout-${today}`, handoutDoc(pack, today, profile, locale), profile)
            }
          >
            {t.quizPrintHandout}
          </button>
        </div>
      </div>

      <div className="panel">
        <div className="panel-head">
          <h2 style={{ margin: 0 }}>{t.quizLogTitle}</h2>
          {records.length > 0 && (
            <button
              className="ghost"
              onClick={() =>
                printDocument(
                  `schulungsregister-${today}`,
                  trainingLogDoc(records, pack, today, profile, locale),
                  profile,
                )
              }
            >
              {t.quizLogPrint}
            </button>
          )}
        </div>
        <p className="hint">{t.quizLogHint}</p>
        {records.length === 0 ? (
          <p className="hint">{t.quizLogEmpty}</p>
        ) : (
          <div className="table-scroll">
            <table>
              <thead>
                <tr>
                  <th>{t.colUpdated}</th>
                  <th>{t.colOwner}</th>
                  <th>{t.quizColScore}</th>
                  <th>{t.quizColStatus}</th>
                </tr>
              </thead>
              <tbody>
                {records.map((r) => (
                  <tr key={r.id}>
                    <td>{uiDate(r.date, locale)}</td>
                    <td>{r.name}</td>
                    <td>{r.scorePct} %</td>
                    <td>
                      <span className={`badge ${r.passed ? 'minimal' : 'high'}`}>
                        {r.passed ? t.quizPassed : t.quizFailed}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
