"use client";

import { clientAuthFetch } from "@/app/utils/clientAuthFetch";
import { NEXT_PUBLIC_API_URL } from "@/config/api";
import { useCallback, useEffect, useState } from "react";

const POLL_MS = 60_000;

const ALERTS_URL = `${NEXT_PUBLIC_API_URL}/product-process/Demo/Process/alerts/fg-qc-putaway`;

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 parseRow(o: Record<string, unknown>): JobOrderFgAlertItem {
  return {
    stockInLineId: Number(o.stockInLineId ?? o.stockinLineId ?? 0),
    jobOrderId: Number(o.jobOrderId ?? o.joborderid ?? 0),
    jobOrderCode: o.jobOrderCode != null ? String(o.jobOrderCode) : null,
    itemNo: o.itemNo != null ? String(o.itemNo) : null,
    itemName: o.itemName != null ? String(o.itemName) : null,
    status: o.status != null ? String(o.status) : null,
    processDate: o.processDate != null ? String(o.processDate) : null,
    lotNo: o.lotNo != null ? String(o.lotNo) : null,
  };
}

function parsePayload(raw: unknown): { qc: JobOrderFgAlertItem[]; putAway: JobOrderFgAlertItem[] } {
  if (!raw || typeof raw !== "object") return { qc: [], putAway: [] };
  const p = raw as Record<string, unknown>;
  const qcRaw = p.qc;
  const putAwayRaw = p.putAway;
  return {
    qc: Array.isArray(qcRaw) ? qcRaw.map((r) => parseRow(r as Record<string, unknown>)) : [],
    putAway: Array.isArray(putAwayRaw)
      ? putAwayRaw.map((r) => parseRow(r as Record<string, unknown>))
      : [],
  };
}

/**
 * 與「完成QC工單」相同資格 + 產程日期為今日或昨日；分待 QC / 待上架。
 */
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 res = await clientAuthFetch(ALERTS_URL);
      if (!res.ok) {
        setQcItems([]);
        setPutAwayItems([]);
        return;
      }
      const data = parsePayload(await res.json());
      setQcItems(data.qc);
      setPutAwayItems(data.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 };
}
