import { useCallback, useMemo, type MouseEvent } from "react";
import type { ReviewSampleAnalysis } from "../../../../lib/reviewSampleAnalysis";
import type { ScanReviewQueueModalProps } from "../types";

export interface ScanReviewQueueRow {
  label: string;
  value: string;
}

export interface ScanReviewQueueModalModel {
  closeReviewQueue: () => void;
  refreshReviewQueue: () => void;
  stopPropagation: (event: MouseEvent<HTMLDivElement>) => void;
  emptyText: string;
  reviewAnalysisRows: ScanReviewQueueRow[];
  showReviewAnalysis: boolean;
}

interface UseScanReviewQueueModalModelInput extends Pick<
  ScanReviewQueueModalProps,
  "setReviewQueueOpen" | "loadReviewQueue"
> {
  reviewAnalysis: ReviewSampleAnalysis;
  reviewSampleTotal: number;
}

export function useScanReviewQueueModalModel({
  setReviewQueueOpen,
  loadReviewQueue,
  reviewAnalysis,
  reviewSampleTotal,
}: UseScanReviewQueueModalModelInput): ScanReviewQueueModalModel {
  const closeReviewQueue = useCallback(() => setReviewQueueOpen(false), [setReviewQueueOpen]);
  const refreshReviewQueue = useCallback(() => {
    void loadReviewQueue();
  }, [loadReviewQueue]);
  const stopPropagation = useCallback((event: MouseEvent<HTMLDivElement>) => {
    event.stopPropagation();
  }, []);

  const weakFieldsSummary = useMemo(
    () => reviewAnalysis.weakFields.slice(0, 3).map((entry) => `${entry.field} ${entry.count}`).join(", "),
    [reviewAnalysis.weakFields],
  );
  const topReasonsSummary = useMemo(
    () => reviewAnalysis.reasons.slice(0, 2).map((entry) => `${entry.reason} ${entry.count}`).join(", "),
    [reviewAnalysis.reasons],
  );

  const reviewAnalysisRows = useMemo(
    () => [
      { label: "Parsed", value: `${reviewAnalysis.withParsed}/${reviewAnalysis.total}` },
      { label: "Avg confidence", value: `${reviewAnalysis.averageConfidence}%` },
      { label: "Weak fields", value: weakFieldsSummary || "none" },
      { label: "Top reasons", value: topReasonsSummary || "none" },
    ],
    [reviewAnalysis.averageConfidence, reviewAnalysis.total, reviewAnalysis.withParsed, topReasonsSummary, weakFieldsSummary],
  );

  return {
    closeReviewQueue,
    refreshReviewQueue,
    stopPropagation,
    emptyText: reviewSampleTotal > 0 ? "none" : "Keine Review-Samples",
    reviewAnalysisRows,
    showReviewAnalysis: reviewSampleTotal > 0,
  };
}
