"use client";

import { useState, useCallback, useEffect, useMemo } from "react";
import { DataGrid, type GridColumn } from "@/components/grid/data-grid";
import { SearchForm, SearchField } from "@/components/layout/search-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { SearchableSelect } from "@/components/ui/searchable-select";
import { ExcelDownloadButton } from "@/components/ui/excel-download-button";
import Swal from "sweetalert2";

// 자재관리 > 불출의뢰서 (원본 /inventoryMng/materialRequestList.do)
export default function InventoryRequestPage() {
  const [partNo, setPartNo] = useState("");
  const [partName, setPartName] = useState("");
  const [requestStartDate, setRequestStartDate] = useState("");
  const [requestEndDate, setRequestEndDate] = useState("");
  const [requestUser, setRequestUser] = useState("");
  const [receptionStatus, setReceptionStatus] = useState("");
  const [receptionUser, setReceptionUser] = useState("");
  const [receptionStartDate, setReceptionStartDate] = useState("");
  const [receptionEndDate, setReceptionEndDate] = useState("");
  const [outStatus, setOutStatus] = useState("");

  const [userOptions, setUserOptions] = useState<{ value: string; label: string }[]>([]);
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetch("/api/admin/users", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({}),
    })
      .then((r) => r.json())
      .then((j) => {
        const list = (j.RESULTLIST || []) as Array<Record<string, unknown>>;
        setUserOptions(
          list.map((r) => ({
            value: String(r.USER_ID || ""),
            label: String(r.USER_NAME || r.USER_ID || ""),
          })),
        );
      })
      .catch(() => setUserOptions([]));
  }, []);

  const openDetailPopup = useCallback(
    (objId: string, outStatusTitle: string, receptionStatusTitle: string) => {
      const w = 1800;
      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: objId,
        action: "view",
        OUTSTATUS: outStatusTitle,
        RECEPTION_STATUS: receptionStatusTitle,
      });
      window.open(
        `/inventory/request/detail?${params.toString()}`,
        "inventoryRequestPopUp",
        `width=${w},height=${h},left=${left},top=${top}`,
      );
    },
    [],
  );

  const columns: GridColumn[] = useMemo(
    () => [
      {
        title: "자재불출번호",
        field: "INVENTORY_OUT_NO",
        width: 140,
        hozAlign: "left",
        headerHozAlign: "center",
        formatter: (cell, row) => (
          <a
            href="#"
            onClick={(e) => {
              e.preventDefault();
              openDetailPopup(
                String(row.OBJID || ""),
                String(row.OUTSTATUS_TITLE || ""),
                String(row.RECEPTION_STATUS_TITLE || ""),
              );
            }}
            className="text-blue-600 underline"
          >
            {String(cell || "")}
          </a>
        ),
      },
      { title: "품번", field: "PART_NO_ARR", width: 480, hozAlign: "left", headerHozAlign: "center" },
      { title: "품명", field: "PART_NAME_ARR", width: 480, hozAlign: "left", headerHozAlign: "center" },
      { title: "불출의뢰일", field: "REQUEST_DATE", width: 120, hozAlign: "left", headerHozAlign: "center" },
      { title: "의뢰자", field: "REQUEST_USER_NAME", width: 100, hozAlign: "left", headerHozAlign: "center" },
      { title: "상태", field: "RECEPTION_STATUS_TITLE", width: 100, hozAlign: "left", headerHozAlign: "center" },
      { title: "접수자", field: "RECEPTION_USER_NAME", width: 100, hozAlign: "center", headerHozAlign: "center" },
      { title: "접수일", field: "RECEPTION_DATE", width: 100, hozAlign: "center", headerHozAlign: "center" },
      { title: "불출상태", field: "OUTSTATUS_TITLE", width: 100, hozAlign: "center", headerHozAlign: "center" },
    ],
    [openDetailPopup],
  );

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/inventory/request", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          part_no: partNo,
          part_name: partName,
          request_start_date: requestStartDate,
          request_end_date: requestEndDate,
          request_user: requestUser,
          reception_status: receptionStatus,
          reception_user: receptionUser,
          reception_start_date: receptionStartDate,
          reception_end_date: receptionEndDate,
          out_status: outStatus,
        }),
      });
      if (res.ok) {
        const json = await res.json();
        setData(json.RESULTLIST || []);
      }
    } finally {
      setLoading(false);
    }
  }, [
    partNo,
    partName,
    requestStartDate,
    requestEndDate,
    requestUser,
    receptionStatus,
    receptionUser,
    receptionStartDate,
    receptionEndDate,
    outStatus,
  ]);

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

  // 접수 (미접수만 가능)
  const handleReceipt = async () => {
    if (selectedRows.length === 0) {
      Swal.fire("선택된 데이터가 없습니다.");
      return;
    }
    const checkedArr = selectedRows
      .filter((r) => String(r.RECEPTION_STATUS_TITLE) === "미접수")
      .map((r) => String(r.OBJID));
    if (checkedArr.length === 0) {
      Swal.fire("선택된 데이터가 없습니다.");
      return;
    }
    const confirmed = await Swal.fire({
      title: "선택된 데이터를 접수하시겠습니까?",
      icon: "warning",
      showCancelButton: true,
      confirmButtonText: "확인",
      cancelButtonText: "취소",
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
    });
    if (!confirmed.isConfirmed) return;

    const res = await fetch("/api/inventory/request/receipt", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ checkArr: checkedArr.join(",") }),
    });
    const data = await res.json();
    Swal.fire(data.message || "접수되었습니다.");
    if (data.success) fetchData();
  };

  // 자재불출 (단일 선택, 접수 상태만)
  const handleAccept = () => {
    if (selectedRows.length === 0) {
      Swal.fire("선택된 데이터가 없습니다.");
      return;
    }
    if (selectedRows.length > 1) {
      Swal.fire("한번에 1개의 내용만 불출가능합니다.");
      return;
    }
    const row = selectedRows[0];
    const receptionStatusTitle = String(row.RECEPTION_STATUS_TITLE || "");
    const outStatusTitle = String(row.OUTSTATUS_TITLE || "");

    if (receptionStatusTitle !== "접수") {
      Swal.fire("접수한 데이터만 불출가능합니다.");
      return;
    }
    if (outStatusTitle === "완료") {
      Swal.fire("불출완료된 데이터는 불출가능합니다.");
      return;
    }

    const w = 1800;
    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: String(row.OBJID || ""),
      OUTSTATUS: outStatusTitle,
      RECEPTION_STATUS: receptionStatusTitle,
    });
    window.open(
      `/inventory/request/detail?${params.toString()}`,
      "inventoryRequestPopUp",
      `width=${w},height=${h},left=${left},top=${top}`,
    );
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-800">자재관리_불출의뢰서</h2>
        <div className="flex gap-2">
          <Button size="sm" onClick={handleAccept}>
            자재불출
          </Button>
          <Button size="sm" variant="secondary" onClick={handleReceipt}>
            접수
          </Button>
          <Button size="sm" variant="secondary" onClick={fetchData}>
            조회
          </Button>
          <ExcelDownloadButton data={data} columns={columns} filename="자재관리_불출의뢰서" />
        </div>
      </div>

      <SearchForm onSearch={fetchData}>
        <SearchField label="품번">
          <Input
            value={partNo}
            onChange={(e) => setPartNo(e.target.value)}
            placeholder="품번"
            className="w-[150px]"
          />
        </SearchField>
        <SearchField label="품명">
          <Input
            value={partName}
            onChange={(e) => setPartName(e.target.value)}
            placeholder="품명"
            className="w-[150px]"
          />
        </SearchField>
        <SearchField label="불출의뢰일">
          <div className="flex items-center gap-1">
            <Input
              type="date"
              value={requestStartDate}
              onChange={(e) => setRequestStartDate(e.target.value)}
              className="w-[130px]"
            />
            <span>~</span>
            <Input
              type="date"
              value={requestEndDate}
              onChange={(e) => setRequestEndDate(e.target.value)}
              className="w-[130px]"
            />
          </div>
        </SearchField>
        <SearchField label="의뢰자">
          <SearchableSelect
            options={userOptions}
            value={requestUser}
            onChange={setRequestUser}
            className="w-[130px]"
          />
        </SearchField>
        <SearchField label="접수상태">
          <select
            value={receptionStatus}
            onChange={(e) => setReceptionStatus(e.target.value)}
            className="h-9 w-[130px] rounded border border-gray-300 bg-white px-3 text-sm"
          >
            <option value="">전체</option>
            <option value="reception">접수</option>
            <option value="AA">미접수</option>
          </select>
        </SearchField>
        <SearchField label="접수자">
          <SearchableSelect
            options={userOptions}
            value={receptionUser}
            onChange={setReceptionUser}
            className="w-[130px]"
          />
        </SearchField>
        <SearchField label="접수일">
          <div className="flex items-center gap-1">
            <Input
              type="date"
              value={receptionStartDate}
              onChange={(e) => setReceptionStartDate(e.target.value)}
              className="w-[130px]"
            />
            <span>~</span>
            <Input
              type="date"
              value={receptionEndDate}
              onChange={(e) => setReceptionEndDate(e.target.value)}
              className="w-[130px]"
            />
          </div>
        </SearchField>
        <SearchField label="불출상태">
          <select
            value={outStatus}
            onChange={(e) => setOutStatus(e.target.value)}
            className="h-9 w-[130px] rounded border border-gray-300 bg-white px-3 text-sm"
          >
            <option value="">선택</option>
            <option value="complete">완료</option>
            <option value="NG">미완료</option>
          </select>
        </SearchField>
      </SearchForm>

      <DataGrid
        columns={columns}
        data={data}
        showCheckbox
        loading={loading}
        onSelectionChange={setSelectedRows}
      />
    </div>
  );
}
