import { useCoreServices } from '@learnitive/context';
import type { LatexDiagnostic } from '@learnitive/latex-compiler';
import { Button } from '@learnitive/ui-components';
import { WsPath } from '@learnitive/ws-path';
import { AlertCircle, ExternalLink, Info, TriangleAlert } from 'lucide-react';
import React from 'react';

function DiagnosticIcon({ severity }: { severity: LatexDiagnostic['severity'] }) {
  if (severity === 'error') return <AlertCircle className="mt-0.5 size-4 shrink-0 text-destructive" />;
  if (severity === 'warning') return <TriangleAlert className="mt-0.5 size-4 shrink-0 text-amber-600" />;
  return <Info className="mt-0.5 size-4 shrink-0 text-muted-foreground" />;
}

export function CompilerDiagnosticsList({
  wsName,
  diagnostics,
  onOpenSource,
}: {
  wsName: string;
  diagnostics: readonly LatexDiagnostic[];
  onOpenSource?: () => void;
}) {
  const { latexSource, navigation } = useCoreServices();
  if (!diagnostics.length) return null;

  const openDiagnostic = (diagnostic: LatexDiagnostic) => {
    if (!diagnostic.file) return;
    const wsPath = WsPath.fromParts(wsName, diagnostic.file).wsPath;
    onOpenSource?.();
    latexSource.requestSelect(wsPath, diagnostic.line ?? 1, diagnostic.column);
    navigation.goWsFile(wsPath);
  };

  return (
    <section className="border-b bg-background" aria-label={t.app.compile.diagnostics} data-testid="interactive-compiler-diagnostics">
      <div className="border-b px-3 py-1.5 text-xs font-medium">{t.app.compile.diagnostics} · {diagnostics.length}</div>
      <div className="max-h-56 overflow-auto divide-y">
        {diagnostics.map((diagnostic) => {
          const location = diagnostic.file
            ? `${diagnostic.file}${diagnostic.line ? `:${diagnostic.line}${diagnostic.column ? `:${diagnostic.column}` : ''}` : ''}`
            : undefined;
          return (
            <div key={`${diagnostic.code ?? diagnostic.severity}:${diagnostic.file ?? ''}:${diagnostic.line ?? ''}:${diagnostic.column ?? ''}:${diagnostic.message}:${diagnostic.raw ?? ''}`} className="flex items-start gap-2 px-3 py-2">
              <DiagnosticIcon severity={diagnostic.severity} />
              <button
                type="button"
                disabled={!diagnostic.file}
                className="min-w-0 flex-1 text-left disabled:cursor-default"
                onClick={() => openDiagnostic(diagnostic)}
              >
                <span className="block text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">{diagnostic.severity}{diagnostic.code ? ` · ${diagnostic.code}` : ''}</span>
                <span className="block text-sm">{diagnostic.message}</span>
                {location && <span className="block font-mono text-[11px] text-muted-foreground">{location}</span>}
              </button>
              {diagnostic.file && (
                <Button size="sm" variant="ghost" onClick={() => openDiagnostic(diagnostic)}>
                  <ExternalLink className="mr-1 size-3.5" />{t.app.compile.openSource}
                </Button>
              )}
            </div>
          );
        })}
      </div>
    </section>
  );
}
