import { FieldConfidenceList } from "../ScanResultCards";
import type { ScanDetailsModalProps } from "./types";
import { useScanDetailsModalModel } from "./hooks/useScanDetailsModalModel";

export function ScanDetailsModal({
  open,
  latestCapture,
  controller,
  setDetailsOpen,
}: ScanDetailsModalProps) {
  const { parsedArtifact } = controller;
  const {
    closeDetails,
    stopPropagation,
    parsedNotes,
    showParsedNotes,
    cropRows,
    ocrRows,
    debugText,
    showCrops,
    showOcr,
  } = useScanDetailsModalModel({
    setDetailsOpen,
    parsedArtifact,
    latestCapture,
  });

  if (!open || !latestCapture) return null;

  return (
    <div className="modal-backdrop" role="presentation" onClick={closeDetails}>
      <div className="modal-panel" role="dialog" aria-modal="true" onClick={stopPropagation}>
        <div className="modal-header">
          <div>
            <p className="eyebrow">Dev</p>
            <h2>Crops, OCR & Confidence</h2>
          </div>
          <button className="ghost-button" onClick={closeDetails}>Schliessen</button>
        </div>
        <div className="modal-body">
          {parsedArtifact && (
            <>
              <FieldConfidenceList parsedArtifact={parsedArtifact} />
              {showParsedNotes && (
                <div className="parsed-notes compact">
                  {parsedNotes.map((note) => <span key={note}>{note}</span>)}
                </div>
              )}
            </>
          )}
          {showCrops && (
            <div className="crop-grid details-grid">
              {cropRows.map((crop) => (
                <div className="crop-card" key={crop.id}>
                  <img src={crop.dataUrl} alt={crop.label} />
                  <div>
                    <strong>{crop.label}</strong>
                    <span>{crop.x},{crop.y} - {crop.width}x{crop.height}</span>
                  </div>
                </div>
              ))}
            </div>
          )}
          {showOcr && (
            <div className="ocr-panel">
              <strong>OCR candidates</strong>
              {ocrRows.map((entry) => (
                <div className="ocr-row" key={entry.id}>
                  <div>
                    <span>{entry.label}</span>
                    <small>{entry.confidence}% confidence</small>
                  </div>
                  <pre>{entry.text}</pre>
                </div>
              ))}
            </div>
          )}
          <p className="capture-debug">{debugText}</p>
        </div>
      </div>
    </div>
  );
}
