import { useEffect } from "react";
import type { Dispatch, SetStateAction } from "react";
import type { CaptureResult } from "../../../types/global";
import type { StoredArtifactRecord } from "../../../types/storage";
import type { ArtifactRepositoryPort } from "../../../infrastructure/repositories/rendererBridgeRepositoryTypes";
import { clampScanLimit } from "../../../lib/scannerSession";

interface ScanViewStateSyncInput {
  artifactRepo?: ArtifactRepositoryPort;
  latestCapture: CaptureResult | null;
  scanLimitTouched: boolean;
  storedTotal: number | null;
  setScanLimit: Dispatch<SetStateAction<number>>;
  setStoredTotal: Dispatch<SetStateAction<number | null>>;
  setRecentArtifacts: Dispatch<SetStateAction<StoredArtifactRecord[]>>;
}

export function useScanViewStateSync({
  artifactRepo,
  latestCapture,
  scanLimitTouched,
  storedTotal,
  setScanLimit,
  setStoredTotal,
  setRecentArtifacts,
}: ScanViewStateSyncInput) {
  useEffect(() => {
    const detectedCount = latestCapture?.inventoryCount?.total ?? latestCapture?.inventoryCount?.current ?? 0;
    if (!scanLimitTouched && detectedCount > 0) {
      setScanLimit(clampScanLimit(detectedCount));
    }
  }, [latestCapture?.inventoryCount?.current, scanLimitTouched, setScanLimit]);

  useEffect(() => {
    artifactRepo?.loadAll().then((result) => {
      if (!result?.ok) return;
      setStoredTotal(result.total);
      setRecentArtifacts(
        [...result.artifacts]
          .sort((left, right) => {
            const rightTime = Date.parse(right.lastSeenAt ?? right.firstSeenAt ?? "") || 0;
            const leftTime = Date.parse(left.lastSeenAt ?? left.firstSeenAt ?? "") || 0;
            return rightTime - leftTime;
          })
          .slice(0, 6),
      );
    }).catch(() => undefined);
  }, [artifactRepo, setRecentArtifacts, setStoredTotal, storedTotal]);
}
