import { useMemo } from 'react';
import { buildChecklist } from '../engine/checklist';
import type { ChecklistEntry } from '../engine/checklist';
import { checklistIcs } from '../engine/ics';
import type { AISystem, CompanyProfile } from '../engine/types';
import { useI18n } from '../i18n/context';
import { fmt } from '../i18n/ui';
import { downloadText, todayISO, uiDate } from './common';

interface ChecklistViewProps {
  readonly systems: readonly AISystem[];
  readonly profile: CompanyProfile;
  readonly onToggle: (systemId: string, obligationId: string, done: boolean) => void;
  readonly onOpenSystem: (systemId: string) => void;
}

function Group({
  title,
  entries,
  emptyText,
  onToggle,
  onOpenSystem,
}: {
  readonly title: string;
  readonly entries: readonly ChecklistEntry[];
  readonly emptyText: string;
  readonly onToggle: (systemId: string, obligationId: string, done: boolean) => void;
  readonly onOpenSystem: (systemId: string) => void;
}): JSX.Element {
  const { locale, t } = useI18n();
  return (
    <div className="panel">
      <h2 style={{ marginTop: 0 }}>
        {title} ({entries.length})
      </h2>
      {entries.length === 0 ? (
        <p className="hint">{emptyText}</p>
      ) : (
        <ul className="task-list">
          {entries.map((e) => (
            <li key={`${e.systemId}:${e.obligation.id}`} className={e.resolved ? 'task done' : 'task'}>
              <label className="task-check">
                <input
                  type="checkbox"
                  checked={e.resolved}
                  onChange={(ev) => onToggle(e.systemId, e.obligation.id, ev.target.checked)}
                />
              </label>
              <div className="task-body">
                <div className="task-title">{e.obligation.title}</div>
                <div className="task-meta">
                  <button className="task-system" onClick={() => onOpenSystem(e.systemId)}>
                    {e.systemName}
                  </button>
                  <span>{e.obligation.articles}</span>
                  <span>
                    {t.tasksDue}: {uiDate(e.obligation.deadline, locale)}
                  </span>
                </div>
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

/**
 * Systemübergreifende, abhakbare Aufgabenliste: was erledigt ist,
 * was jetzt fällig ist und was noch kommt — mobiltauglich.
 */
export function ChecklistView({
  systems,
  profile,
  onToggle,
  onOpenSystem,
}: ChecklistViewProps): JSX.Element {
  const { t, pack } = useI18n();
  const today = todayISO();

  const checklist = useMemo(
    () => buildChecklist(systems, pack, profile.countries, today),
    [systems, pack, profile.countries, today],
  );

  const pct = checklist.total === 0 ? 0 : Math.round((checklist.resolvedCount / checklist.total) * 100);

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

      {checklist.total === 0 ? (
        <div className="panel">
          <div className="empty">{t.tasksEmpty}</div>
        </div>
      ) : (
        <>
          <div className="panel">
            <div className="progress-label">
              {fmt(t.tasksProgress, { done: checklist.resolvedCount, total: checklist.total })} — {pct} %
            </div>
            <div className="progress-track">
              <div className="progress-fill" style={{ width: `${pct}%` }} />
            </div>
            <div className="toolbar" style={{ margin: '14px 0 0' }}>
              <button
                className="ghost"
                onClick={() =>
                  downloadText(
                    `ai-act-fristen-${today}.ics`,
                    checklistIcs({
                      entries: [...checklist.dueNow, ...checklist.upcoming],
                      deadlines: pack.deadlines,
                      today,
                      timestamp: new Date().toISOString(),
                      calendarName: 'AI-Act-Kompass',
                    }),
                    'text/calendar',
                  )
                }
              >
                {t.calExport}
              </button>
            </div>
            <p className="hint" style={{ marginBottom: 0 }}>
              {t.calHint}
            </p>
          </div>

          <Group
            title={t.tasksDueNow}
            entries={checklist.dueNow}
            emptyText={t.tasksAllDone}
            onToggle={onToggle}
            onOpenSystem={onOpenSystem}
          />
          <Group
            title={t.tasksUpcoming}
            entries={checklist.upcoming}
            emptyText={t.tasksAllDone}
            onToggle={onToggle}
            onOpenSystem={onOpenSystem}
          />
          <Group
            title={t.tasksResolved}
            entries={checklist.resolved}
            emptyText="—"
            onToggle={onToggle}
            onOpenSystem={onOpenSystem}
          />
        </>
      )}
    </div>
  );
}
