import { useCallback } from "react";
import type { ScanMainSectionProps } from "../types";
import type { StoredArtifactRecord, StoredScanResultEntry } from "../../../../types/storage";

export interface ScanResultRailRow {
  id: string;
  sequence: string;
  title: string;
  meta: string;
  score: string;
  statusLabel: string;
  statusClassName: string;
}

export interface ScanMainSectionModel {
  canOpenDetails: boolean;
  handleOpenDetails: () => void;
  handleOpenInventory: () => void;
  handleOpenReviewQueue: () => void;
  captureImageSrc: string;
  captureImageAlt: string;
  hasCapture: boolean;
  resultHeading: string;
  noArtifactText: string;
  noCaptureMessage: string;
  targetLabel: string;
  dbLabel: string;
  reviewLabel: string;
  recentRows: ScanResultRailRow[];
  recentEmptyText: string;
  canOpenInventory: boolean;
}

type UseScanMainSectionModelProps = Pick<
  ScanMainSectionProps,
  | "latestCapture"
  | "parsedArtifact"
  | "recentArtifacts"
  | "nativeScanResults"
  | "activeTargetCount"
  | "storedTotal"
  | "reviewSampleTotal"
  | "setDetailsOpen"
  | "openReviewQueue"
  | "openInventory"
>;

export function useScanMainSectionModel({
  latestCapture,
  parsedArtifact,
  recentArtifacts,
  nativeScanResults,
  activeTargetCount,
  storedTotal,
  reviewSampleTotal,
  setDetailsOpen,
  openReviewQueue,
  openInventory,
}: UseScanMainSectionModelProps): ScanMainSectionModel {
  const handleOpenDetails = useCallback(() => {
    setDetailsOpen(true);
  }, [setDetailsOpen]);
  const handleOpenInventory = useCallback(() => {
    openInventory?.();
  }, [openInventory]);
  const handleOpenReviewQueue = useCallback(() => {
    void openReviewQueue();
  }, [openReviewQueue]);
  const canOpenDetails = Boolean(latestCapture?.crops?.length || latestCapture?.ocr?.length);
  const captureImageSrc = latestCapture ? latestCapture.detailDataUrl ?? latestCapture.dataUrl : "";
  const captureImageAlt = latestCapture
    ? `Latest capture from ${latestCapture.name}`
    : "Latest capture is not available yet";
  const resultHeading = parsedArtifact ? parsedArtifact.name : "Noch kein Artifact";
  const noArtifactText = "Oeffne ein Artifact in Genshin und nutze \"Einzelnes Artifact lesen\" - oder starte direkt den Auto-Scan.";
  const noCaptureMessage = noArtifactText;
  const targetLabel = `Ziel ${activeTargetCount}`;
  const dbLabel = `DB ${storedTotal ?? "-"}`;
  const reviewLabel = `Review ${reviewSampleTotal}`;
  const nativeRows = nativeScanResults
    .slice(-6)
    .reverse()
    .map(nativeScanResultToRailRow);
  const storedRows = recentArtifacts.map(storedArtifactToRailRow);
  const recentRows = nativeRows.length > 0 ? nativeRows : storedRows;
  const recentEmptyText = nativeRows.length > 0
    ? "Native Ergebnisse werden geladen."
    : "Noch keine gespeicherten Scan-Ergebnisse.";

  return {
    canOpenDetails,
    handleOpenDetails,
    handleOpenInventory,
    handleOpenReviewQueue,
    captureImageSrc,
    captureImageAlt,
    hasCapture: Boolean(latestCapture),
    resultHeading,
    noArtifactText,
    noCaptureMessage,
    targetLabel,
    dbLabel,
    reviewLabel,
    recentRows,
    recentEmptyText,
    canOpenInventory: Boolean(openInventory && recentRows.length > 0),
  };
}

function storedArtifactToRailRow(artifact: StoredArtifactRecord, index: number): ScanResultRailRow {
    const statusLabel = artifact.needsReview
      ? "Review"
      : (artifact.timesSeen ?? 1) > 1
        ? "Duplikat"
        : "Gelesen";
    const statusClassName = artifact.needsReview
      ? "review"
      : (artifact.timesSeen ?? 1) > 1
        ? "duplicate"
        : "stored";
    const levelText = typeof artifact.level === "number" ? `+${artifact.level}` : "+?";
    return {
      id: artifact.id,
      sequence: `#${index + 1}`,
      title: artifact.name || `${artifact.slot} ${artifact.setName}`,
      meta: `${artifact.slot} - ${artifact.mainStat} - ${levelText}`,
      score: artifact.needsReview ? "Review" : "Wert offen",
      statusLabel,
      statusClassName,
    };
}

function nativeScanResultToRailRow(entry: StoredScanResultEntry): ScanResultRailRow {
  const artifact = entry.artifact;
  const levelText = typeof artifact?.level === "number" ? `+${artifact.level}` : "+?";
  const isClean = entry.extractionStatus === "parsed" && !entry.needsReview;
  const statusLabel = isClean
    ? entry.persistedArtifact ? "Gespeichert" : "Geparst"
    : entry.extractionStatus === "missing_crop"
      ? "Crop fehlt"
      : "Review";
  const statusClassName = isClean ? entry.persistedArtifact ? "stored" : "parsed" : "review";

  return {
    id: entry.id,
    sequence: `#${entry.sequence}`,
    title: artifact?.name || `Artifact ${entry.sequence}`,
    meta: artifact
      ? `${artifact.slot} - ${artifact.mainStat} - ${levelText}`
      : entry.error || entry.extractionStatus,
    score: entry.valueStatus === "deferred" ? "Wert offen" : "Review",
    statusLabel,
    statusClassName,
  };
}
