import { useMemo, useState } from 'react';
import { docStrings } from '../engine/docStrings';
import { actionPlan, annexIVSkeleton, riskReport } from '../engine/documents';
import { conformityDeclaration, procurementSpec } from '../engine/extraDocs';
import { deriveObligations } from '../engine/obligations';
import {
  employeeInfo,
  friaTemplate,
  incidentReportForm,
  worksCouncilInfo,
} from '../engine/templatesSystem';
import type { AISystem, CompanyProfile, ObligationStatus } from '../engine/types';
import { useI18n } from '../i18n/context';
import { fmt } from '../i18n/ui';
import { printDocument } from '../print/print';
import { downloadText, RiskBadge, ROLE_UI, todayISO, uiDate } from './common';

interface SystemDetailProps {
  readonly system: AISystem;
  readonly profile: CompanyProfile;
  readonly onUpdate: (system: AISystem) => void;
  readonly onReassess: () => void;
  readonly onDelete: () => void;
  readonly onBack: () => void;
}

type DocKind =
  | 'report'
  | 'plan'
  | 'annexIV'
  | 'procurement'
  | 'conformity'
  | 'worksCouncil'
  | 'employeeInfo'
  | 'fria'
  | 'incident';

/** Detailansicht eines Systems: Klassifizierung, Pflichten-Checkliste, Dokumente. */
export function SystemDetail({
  system,
  profile,
  onUpdate,
  onReassess,
  onDelete,
  onBack,
}: SystemDetailProps): JSX.Element {
  const { t, locale, pack } = useI18n();
  const today = todayISO();
  const [preview, setPreview] = useState<DocKind | null>(null);

  const obligations = useMemo(
    () => deriveObligations(system.classification, system.answers, pack, profile.countries),
    [system, pack, profile.countries],
  );

  const statusOptions: readonly { value: ObligationStatus; label: string }[] = [
    { value: 'open', label: t.statusOpen },
    { value: 'in-progress', label: t.statusInProgress },
    { value: 'done', label: t.statusDone },
    { value: 'not-applicable', label: t.statusNA },
  ];

  const setStatus = (obligationId: string, status: ObligationStatus): void => {
    onUpdate({
      ...system,
      updatedAt: new Date().toISOString(),
      obligationStatus: { ...system.obligationStatus, [obligationId]: status },
    });
  };

  const docs: Record<DocKind, { label: string; file: string; render: () => string }> = {
    report: {
      label: t.docRisk,
      file: `risikobericht-${system.name}-${today}.md`,
      render: () => riskReport(system, pack, today, profile, locale),
    },
    plan: {
      label: t.docPlan,
      file: `massnahmenplan-${system.name}-${today}.md`,
      render: () => actionPlan(system, obligations, pack, today, profile, locale),
    },
    annexIV: {
      label: t.docAnnexIV,
      file: `annex-iv-${system.name}-${today}.md`,
      render: () => annexIVSkeleton(system, pack, today, profile, locale),
    },
    procurement: {
      label: t.docProcurement,
      file: `lastenheft-${system.name}-${today}.md`,
      render: () => procurementSpec(system, pack, today, profile, locale),
    },
    conformity: {
      label: t.docConformity,
      file: `konformitaetserklaerung-${system.name}-${today}.md`,
      render: () => conformityDeclaration(system, pack, today, profile, locale),
    },
    worksCouncil: {
      label: t.docWorksCouncil,
      file: `betriebsrat-info-${system.name}-${today}.md`,
      render: () => worksCouncilInfo(system, pack, today, profile, locale),
    },
    employeeInfo: {
      label: t.docEmployeeInfo,
      file: `mitarbeiterinfo-${system.name}-${today}.md`,
      render: () => employeeInfo(system, pack, today, profile, locale),
    },
    fria: {
      label: t.docFria,
      file: `fria-${system.name}-${today}.md`,
      render: () => friaTemplate(system, pack, today, profile, locale),
    },
    incident: {
      label: t.docIncident,
      file: `vorfallmeldung-${system.name}-${today}.md`,
      render: () => incidentReportForm(system, pack, today, profile, locale),
    },
  };

  const isProvider = system.answers.role === 'provider';
  const isDeployer = system.answers.role === 'deployer';
  const isHigh = system.classification.riskClass === 'high';
  const visibleDocs = (Object.keys(docs) as DocKind[]).filter((kind) => {
    if (kind === 'annexIV' || kind === 'conformity') return isHigh && isProvider;
    if (kind === 'procurement') return isDeployer;
    if (kind === 'worksCouncil') return isDeployer && profile.countries.includes('DE');
    if (kind === 'employeeInfo') return isDeployer;
    if (kind === 'fria') return isDeployer && isHigh;
    if (kind === 'incident') return isHigh;
    return true;
  });

  const nationalCodes = profile.countries.filter((code) =>
    pack.national.some((n) => n.code === code),
  );

  return (
    <div>
      <button className="ghost" onClick={onBack}>
        {t.detailBack}
      </button>
      <h1 style={{ marginTop: 14 }}>
        {system.name} <RiskBadge risk={system.classification.riskClass} />
      </h1>
      <p className="sub">
        {ROLE_UI[locale][system.answers.role]} · {system.purpose || t.detailNoPurpose}
      </p>

      <div className="panel">
        <h2 style={{ marginTop: 0 }}>{t.detailReasons}</h2>
        <ul className="reasons">
          {system.classification.reasons.map((r) => (
            <li key={r}>{r}</li>
          ))}
        </ul>
        <div className="toolbar">
          <button className="ghost" onClick={onReassess}>
            {t.detailReassess}
          </button>
          <button className="danger" onClick={onDelete}>
            {t.detailDelete}
          </button>
        </div>
      </div>

      {obligations.length > 0 && (
        <div className="panel">
          <h2 style={{ marginTop: 0 }}>
            {t.detailObligations} ({obligations.length})
            {nationalCodes.length > 0 && (
              <span className="hint"> — {fmt(t.detailNational, { codes: nationalCodes.join(', ') })}</span>
            )}
          </h2>
          <div className="table-scroll">
            <table>
              <thead>
                <tr>
                  <th>{docStrings(locale).plan.colObligation}</th>
                  <th>{docStrings(locale).plan.colLegal}</th>
                  <th>{docStrings(locale).plan.colDeadline}</th>
                  <th>{docStrings(locale).plan.colStatus}</th>
                </tr>
              </thead>
              <tbody>
                {obligations.map((ob) => {
                  const status = system.obligationStatus[ob.id] ?? 'open';
                  return (
                    <tr key={ob.id}>
                      <td>
                        <strong>{ob.title}</strong>
                        <div className="hint">{ob.description}</div>
                      </td>
                      <td>{ob.articles}</td>
                      <td>{uiDate(ob.deadline, locale)}</td>
                      <td>
                        <select
                          value={status}
                          onChange={(e) => setStatus(ob.id, e.target.value as ObligationStatus)}
                        >
                          {statusOptions.map((o) => (
                            <option key={o.value} value={o.value}>
                              {o.label}
                            </option>
                          ))}
                        </select>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}

      <div className="panel">
        <h2 style={{ marginTop: 0 }}>{t.detailDocs}</h2>
        <div className="toolbar">
          {visibleDocs.map((kind) => (
            <span key={kind} style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
              <button className="ghost" onClick={() => setPreview(preview === kind ? null : kind)}>
                {docs[kind].label} {preview === kind ? t.docHide : t.docShow}
              </button>
              <button
                className="primary"
                onClick={() =>
                  printDocument(docs[kind].file.replace(/\.md$/, ''), docs[kind].render(), profile)
                }
              >
                {t.docPrint}
              </button>
              <button className="ghost" onClick={() => downloadText(docs[kind].file, docs[kind].render())}>
                .md
              </button>
            </span>
          ))}
        </div>
        {preview && <pre className="doc-preview">{docs[preview].render()}</pre>}
      </div>
    </div>
  );
}
