"use client";

import {
  AllJoborderProductProcessInfoResponse,
  fetchJoborderProductProcessesPage,
} from "@/app/api/jo/actions";
import dayjs from "dayjs";
import { useCallback, useEffect, useState } from "react";

const POLL_MS = 60_000;
/** Same as ProductionProcessList pending_qc tab. */
export const PRODUCTION_LOOKBACK_DAYS = 4;
const FETCH_SIZE = 200;

export type JobOrderFgAlertItem = {
  stockInLineId: number;
  jobOrderId: number;
  jobOrderCode: string | null;
  itemNo: string | null;
  itemName: string | null;
  status: string | null;
  processDate: string | null;
  lotNo: string | null;
};

function isPutawayCompleted(p: AllJoborderProductProcessInfoResponse): boolean {
  return String(p.stockInLineStatus ?? "").trim().toLowerCase() === "completed";
}

function toAlertItem(p: AllJoborderProductProcessInfoResponse): JobOrderFgAlertItem | null {
  if (!p.stockInLineId || !p.jobOrderId) return null;
  return {
    stockInLineId: p.stockInLineId,
    jobOrderId: p.jobOrderId,
    jobOrderCode: p.jobOrderCode ?? null,
    itemNo: p.itemCode ?? null,
    itemName: p.itemName ?? null,
    status: p.stockInLineStatus ?? null,
    processDate: p.date ?? null,
    lotNo: p.lotNo ?? null,
  };
}

function splitPendingQcRows(content: AllJoborderProductProcessInfoResponse[]): {
  qc: JobOrderFgAlertItem[];
  putAway: JobOrderFgAlertItem[];
} {
  const qc: JobOrderFgAlertItem[] = [];
  const putAway: JobOrderFgAlertItem[] = [];

  for (const p of content) {
    if (isPutawayCompleted(p)) continue;
    const item = toAlertItem(p);
    if (!item) continue;
    const statusNorm = String(p.stockInLineStatus ?? "").trim().toLowerCase();
    if (statusNorm === "received" || statusNorm === "partially_completed") {
      putAway.push(item);
    } else {
      qc.push(item);
    }
  }

  const sortByDate = (a: JobOrderFgAlertItem, b: JobOrderFgAlertItem) =>
    (b.processDate ?? "").localeCompare(a.processDate ?? "");

  qc.sort(sortByDate);
  putAway.sort(sortByDate);
  return { qc, putAway };
}

/**
 * 與產程「待 QC 上架」tab 相同 API／日期（今日、lookback 4 天）；分待 QC / 待上架。
 */
/** FP-MTMS Version Checklist | Functions Ref. No. 52 | v1.0.0 | 2026-08-05 */
export function useJobOrderFgStockInAlerts(enabled: boolean) {
  const [qcItems, setQcItems] = useState<JobOrderFgAlertItem[]>([]);
  const [putAwayItems, setPutAwayItems] = useState<JobOrderFgAlertItem[]>([]);
  const [loading, setLoading] = useState(false);

  const load = useCallback(async () => {
    if (!enabled) {
      setQcItems([]);
      setPutAwayItems([]);
      return;
    }
    setLoading(true);
    try {
      const dateStr = dayjs().format("YYYY-MM-DD");
      const data = await fetchJoborderProductProcessesPage({
        date: dateStr,
        lookbackDays: PRODUCTION_LOOKBACK_DAYS,
        qcReady: true,
        includePutaway: true,
        putawayStatus: "notCompleted",
        page: 0,
        size: FETCH_SIZE,
      });
      const { qc, putAway } = splitPendingQcRows(data?.content ?? []);
      setQcItems(qc);
      setPutAwayItems(putAway);
    } catch {
      setQcItems([]);
      setPutAwayItems([]);
    } finally {
      setLoading(false);
    }
  }, [enabled]);

  useEffect(() => {
    if (!enabled) {
      setQcItems([]);
      setPutAwayItems([]);
      return;
    }
    void load();
    const id = window.setInterval(() => void load(), POLL_MS);
    return () => window.clearInterval(id);
  }, [enabled, load]);

  const count = qcItems.length + putAwayItems.length;

  return { qcItems, putAwayItems, count, loading, reload: load };
}
