import { buildChecklist } from '../engine/checklist';
import { inventoryReport } from '../engine/documents';
import type { AISystem, CompanyProfile } 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 DashboardProps {
  readonly systems: readonly AISystem[];
  readonly profile: CompanyProfile;
  readonly onOpen: (id: string) => void;
  readonly onNew: () => void;
}

/** Übersichtsseite: Kennzahlen, Fristen und das KI-Inventar. */
export function Dashboard({ systems, profile, onOpen, onNew }: DashboardProps): JSX.Element {
  const { t, locale, pack } = useI18n();
  const today = todayISO();
  const count = (risk: string): number =>
    systems.filter((s) => s.classification.riskClass === risk).length;

  const checklist = buildChecklist(systems, pack, profile.countries, today);
  const openTasks = checklist.total - checklist.resolvedCount;

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

      <div className="panel grid">
        <div className="stat">
          <div className="num">{systems.length}</div>
          <div className="lbl">{t.statSystems}</div>
        </div>
        <div className="stat">
          <div className="num">{count('high')}</div>
          <div className="lbl">{t.statHigh}</div>
        </div>
        <div className="stat">
          <div className="num">{count('prohibited')}</div>
          <div className="lbl">{t.statProhibited}</div>
        </div>
        <div className="stat">
          <div className="num">{openTasks}</div>
          <div className="lbl">{t.statOpen}</div>
        </div>
      </div>

      <div className="panel">
        <h2 style={{ marginTop: 0 }}>{t.deadlinesTitle}</h2>
        <ul className="deadline-list">
          {pack.deadlines.map((d) => (
            <li key={d.id}>
              <span className={`date ${d.date < today ? 'past' : ''}`}>{uiDate(d.date, locale)}</span>
              <span>
                <strong>{d.label}</strong> — {d.description}
              </span>
            </li>
          ))}
        </ul>
      </div>

      <div className="panel">
        <div className="panel-head">
          <h2 style={{ margin: 0 }}>{t.inventoryTitle}</h2>
          <div className="toolbar" style={{ margin: 0 }}>
            {systems.length > 0 && (
              <>
                <button
                  className="ghost"
                  onClick={() =>
                    printDocument(
                      `ki-inventar-${today}`,
                      inventoryReport(systems, pack, today, profile, locale),
                      profile,
                    )
                  }
                >
                  {t.inventoryPrint}
                </button>
                <button
                  className="ghost"
                  onClick={() =>
                    downloadText(
                      `ki-inventar-${today}.md`,
                      inventoryReport(systems, pack, today, profile, locale),
                    )
                  }
                >
                  .md
                </button>
              </>
            )}
            <button className="primary" onClick={onNew}>
              {t.newSystem}
            </button>
          </div>
        </div>
        {systems.length === 0 ? (
          <div className="empty">{t.emptyInventory}</div>
        ) : (
          <div className="table-scroll">
            <table>
              <thead>
                <tr>
                  <th>{t.colSystem}</th>
                  <th>{t.colRole}</th>
                  <th>{t.colRisk}</th>
                  <th>{t.colOwner}</th>
                  <th>{t.colUpdated}</th>
                </tr>
              </thead>
              <tbody>
                {systems.map((s) => (
                  <tr key={s.id} className="clickable" onClick={() => onOpen(s.id)}>
                    <td>
                      <strong>{s.name}</strong>
                    </td>
                    <td>{ROLE_UI[locale][s.answers.role]}</td>
                    <td>
                      <RiskBadge risk={s.classification.riskClass} />
                    </td>
                    <td>{s.owner || '—'}</td>
                    <td>{uiDate(s.updatedAt.slice(0, 10), locale)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <p className="disclaimer">{fmt(t.disclaimerLine, { version: pack.version })}</p>
    </div>
  );
}
