import { useCallback, type ChangeEvent, type MouseEvent } from "react";
import type { CaptureResult, RuntimeInfo } from "../../../../../types/global";
import { clampScanLimit, clampSkipRows } from "../../../../lib/scannerSession";

export interface ScanSettingsModalModel {
  closeSettings: () => void;
  handleScanLimitChange: (event: ChangeEvent<HTMLInputElement>) => void;
  handleSkipRowsChange: (event: ChangeEvent<HTMLInputElement>) => void;
  stopPropagation: (event: MouseEvent<HTMLDivElement>) => void;
  inventoryCountText: string;
  inventoryClassName: string;
  scanLimitClassName: string;
  skipRowsClassName: string;
  activeTargetText: string;
  scanSummaryText: string;
}

export function useScanSettingsModalModel({
  setSettingsOpen,
  setScanLimit,
  setScanLimitTouched,
  setSkipRows,
  latestCapture,
  scanLimit,
  skipRows,
  activeTargetCount,
  runtimeInfo,
}: {
  latestCapture: CaptureResult | null;
  scanLimit: number;
  skipRows: number;
  activeTargetCount: number;
  runtimeInfo: RuntimeInfo | null;
  setSettingsOpen: (open: boolean) => void;
  setScanLimit: (value: number) => void;
  setScanLimitTouched: (touched: boolean) => void;
  setSkipRows: (rows: number) => void;
}): ScanSettingsModalModel {
  const closeSettings = useCallback(() => setSettingsOpen(false), [setSettingsOpen]);
  const handleScanLimitChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {
    setScanLimitTouched(true);
    setScanLimit(clampScanLimit(Number(event.target.value)));
  }, [setScanLimit, setScanLimitTouched]);
  const handleSkipRowsChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {
    setSkipRows(clampSkipRows(Number(event.target.value)));
  }, [setSkipRows]);
  const stopPropagation = useCallback((event: MouseEvent<HTMLDivElement>) => {
    event.stopPropagation();
  }, []);
  const detectedInventoryCount = latestCapture?.inventoryCount?.current;
  const detectedInventoryTotal = latestCapture?.inventoryCount?.total;
  const inventoryClassName = detectedInventoryCount ? "ok" : "neutral";
  const inventoryCountText = detectedInventoryCount
    ? `${detectedInventoryCount}/${detectedInventoryTotal || "?"}`
    : "Noch nicht erkannt";
  const scanLimitClassName = scanLimit !== detectedInventoryCount ? "ok" : "standard";
  const skipRowsClassName = skipRows > 0 ? "ok" : "standard";
  const focusModeText = runtimeInfo?.isElevated ? "Admin" : "Standard";
  const activeTargetText = `Aktive Zielvorgabe ${activeTargetCount} und Fokusmodus ${focusModeText}.`;
  const scanSummaryText = "Der Auto-Scan zaehlt \"Positionen\" und \"verified\", bevor die Datenbank in den Save-Pfad laeuft. So wird \"scanned\" nicht mit \"erfolgreich gespeichert\" verwechselt.";

  return {
    closeSettings,
    handleScanLimitChange,
    handleSkipRowsChange,
    stopPropagation,
    inventoryCountText,
    inventoryClassName,
    scanLimitClassName,
    skipRowsClassName,
    activeTargetText,
    scanSummaryText,
  };
}
