"use client";

import { useState, useEffect, useCallback, Suspense } from "react";
import { useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { numberWithCommas } from "@/lib/utils";

// 입출고 History 팝업 (원본 /inventoryMng/inventoryRequestHistoryPopUp.do)
function HistoryPage() {
  const searchParams = useSearchParams();
  const objId = searchParams.get("objId") || searchParams.get("partId") || "";
  const [rows, setRows] = useState<Record<string, unknown>[]>([]);

  const fetchData = useCallback(async () => {
    if (!objId) return;
    const res = await fetch("/api/inventory/request/history", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ objId }),
    });
    if (res.ok) {
      const json = await res.json();
      setRows(json.RESULTLIST || []);
    }
  }, [objId]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const openTarget = (id: string, gubun: string) => {
    if (gubun === "출고") {
      const w = 1500;
      const h = 700;
      const left = (window.screen.width - w) / 2;
      const top = (window.screen.height - h) / 2;
      const params = new URLSearchParams({
        INVENTORY_REQUEST_MASTER_OBJID: id,
        action: "view",
      });
      window.open(
        `/inventory/request/detail?${params.toString()}`,
        "inventoryRequestPopUp",
        `width=${w},height=${h},left=${left},top=${top}`,
      );
    } else if (gubun === "입고") {
      const w = 1260;
      const h = 1050;
      const left = (window.screen.width - w) / 2;
      const top = (window.screen.height - h) / 2;
      window.open(
        `/delivery/acceptance/form?objId=${encodeURIComponent(id)}&actionType=view`,
        "deliveryAcceptancePopUp",
        `width=${w},height=${h},left=${left},top=${top}`,
      );
    }
  };

  return (
    <div className="p-3 bg-white min-h-screen">
      <div className="mb-2">
        <h2 className="text-base font-bold">입출고 이력</h2>
      </div>

      <div className="border border-gray-300 overflow-x-auto max-h-[calc(100vh-120px)]">
        <table className="w-full text-xs">
          <thead className="bg-gray-100 text-center sticky top-0">
            <tr>
              <th className="border px-2 py-1.5">프로젝트번호</th>
              <th className="border px-2 py-1.5">품번</th>
              <th className="border px-2 py-1.5">품명</th>
              <th className="border px-2 py-1.5">구분</th>
              <th className="border px-2 py-1.5">입출고수량</th>
              <th className="border px-2 py-1.5">Location</th>
              <th className="border px-2 py-1.5">Sub_Location</th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 ? (
              <tr>
                <td colSpan={7} className="text-center py-4 text-gray-400">
                  조회된 데이터가 없습니다.
                </td>
              </tr>
            ) : (
              rows.map((r, i) => {
                const gubun = String(r.GUBUN || "");
                const rowObjId = String(r.OBJID || "");
                return (
                  <tr key={i} className="border-b">
                    <td className="border px-2 py-1">{String(r.PROJECT_NO || "")}</td>
                    <td className="border px-2 py-1">{String(r.PART_NO || "")}</td>
                    <td className="border px-2 py-1">{String(r.PART_NAME || "")}</td>
                    <td className="border px-2 py-1 text-center">
                      {gubun === "입고" || gubun === "출고" ? (
                        <a
                          href="#"
                          onClick={(e) => {
                            e.preventDefault();
                            openTarget(rowObjId, gubun);
                          }}
                          className="text-blue-600 underline"
                        >
                          {gubun}
                        </a>
                      ) : (
                        <span>{gubun}</span>
                      )}
                    </td>
                    <td className="border px-2 py-1 text-right">
                      {numberWithCommas(String(r.RECEIPT_QTY || ""))}
                    </td>
                    <td className="border px-2 py-1">{String(r.LOCATION_NAME || "")}</td>
                    <td className="border px-2 py-1">{String(r.SUB_LOCATION_NAME || "")}</td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>

      <div className="flex justify-center mt-3 pt-2 border-t">
        <Button variant="secondary" onClick={() => window.close()}>
          닫기
        </Button>
      </div>
    </div>
  );
}

export default function Page() {
  return (
    <Suspense fallback={<div className="p-8 text-center text-gray-400">로딩 중...</div>}>
      <HistoryPage />
    </Suspense>
  );
}
