"use client";

import { useState, useCallback, useEffect } 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 { SearchableCodeSelect } from "@/components/ui/searchable-code-select";
import Swal from "sweetalert2";

type Option = { value: string; label: string };

// 원본: purchaseOrder/deliveryMngAcceptanceList.jsp
// 입고관리 > 입고결과등록
export default function AcceptancePage() {
  const currentYear = new Date().getFullYear();
  const [year, setYear] = useState("");
  const [customerProjectName, setCustomerProjectName] = useState("");
  const [projectNo, setProjectNo] = useState("");
  const [unitCode, setUnitCode] = useState("");
  const [purchaseOrderNo, setPurchaseOrderNo] = useState("");
  const [type, setType] = useState("");
  const [searchPartSpec, setSearchPartSpec] = useState("");
  const [partnerObjid, setPartnerObjid] = useState("");
  const [salesMngUserId, setSalesMngUserId] = useState("");
  const [deliveryStartDate, setDeliveryStartDate] = useState("");
  const [deliveryEndDate, setDeliveryEndDate] = useState("");
  const [regStartDate, setRegStartDate] = useState("");
  const [regEndDate, setRegEndDate] = useState("");
  const [deliveryStatus, setDeliveryStatus] = useState("");
  const [searchPartName, setSearchPartName] = useState("");
  const [searchPartNo, setSearchPartNo] = useState("");
  const [poClientId, setPoClientId] = useState("");

  const [supplyOptions, setSupplyOptions] = useState<Option[]>([]);
  const [userOptions, setUserOptions] = useState<Option[]>([]);

  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);

  useEffect(() => {
    fetch("/api/admin/supply", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: "{}",
    })
      .then((r) => r.json())
      .then((d) =>
        setSupplyOptions(
          (d.RESULTLIST || []).map((r: Record<string, unknown>) => ({
            value: String(r.OBJID),
            label: String(r.SUPPLY_NAME),
          })),
        ),
      )
      .catch(() => {});

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

  // 발주서 상세 팝업 열기 (발주번호 셀 클릭)
  const openOrderForm = (objId: string) => {
    const w = 1460;
    const h = 1050;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(
      `/order/list/form?objId=${objId}&action=view`,
      `orderForm_${objId}`,
      `width=${w},height=${h},left=${left},top=${top}`,
    );
  };

  // 입고결과 팝업 (view) — 입고결과 셀 클릭
  const openAcceptanceViewPopup = (objId: string, status: string) => {
    const w = 1560;
    const h = 1050;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(
      `/delivery/acceptance/form?objId=${objId}&delivery_status=${encodeURIComponent(status)}`,
      "deliveryAcceptancePopUp",
      `width=${w},height=${h},left=${left},top=${top}`,
    );
  };

  const columns: GridColumn[] = [
    { title: "고객사", field: "CUSTOMER_NAME", width: 110, hozAlign: "left" },
    { title: "프로젝트명", field: "CUSTOMER_PROJECT_NAME", width: 150, hozAlign: "left" },
    { title: "유닛명", field: "UNIT_NAME", width: 200, hozAlign: "left" },
    { title: "프로젝트번호", field: "PROJECT_NO", width: 100, hozAlign: "center" },
    {
      title: "발주번호",
      field: "PURCHASE_ORDER_NO",
      width: 100,
      hozAlign: "center",
      cellClick: (row) => openOrderForm(String(row.OBJID || "")),
    },
    { title: "동시", field: "MULTI_YN_MAKED", width: 50, hozAlign: "center" },
    { title: "발주서_제목", field: "TITLE", width: 150, hozAlign: "left" },
    { title: "입고요청일", field: "DELIVERY_DATE", width: 85, hozAlign: "center" },
    { title: "구매/제작업체명", field: "PARTNER_NAME", width: 120, hozAlign: "left" },
    { title: "구매담당", field: "SALES_MNG_USER_NAME", width: 78, hozAlign: "center" },
    { title: "발주일", field: "REGDATE", width: 78, hozAlign: "center" },
    { title: "발주수량", field: "TOTAL_PO_QTY", width: 78, hozAlign: "right", formatter: "money" },
    { title: "입고일", field: "CUR_DELIVERY_DATE", width: 78, hozAlign: "center" },
    { title: "입고자", field: "CUR_RECEIVER_NAME", width: 70, hozAlign: "center" },
    { title: "입고수량", field: "TOTAL_DELIVERY_QTY", width: 75, hozAlign: "right", formatter: "money" },
    { title: "미입고수량", field: "NON_DELIVERY_QTY", width: 85, hozAlign: "right", formatter: "money" },
    {
      title: "입고결과",
      field: "DELIVERY_STATUS",
      width: 75,
      hozAlign: "center",
      cellClick: (row) =>
        openAcceptanceViewPopup(String(row.OBJID || ""), String(row.DELIVERY_STATUS || "")),
    },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/delivery/acceptance", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year,
        customer_project_name: customerProjectName,
        project_nos: projectNo ? [projectNo] : [],
        unit_code: unitCode,
        purchase_order_no: purchaseOrderNo,
        type,
        SEARCH_PART_SPEC: searchPartSpec,
        partner_objid: partnerObjid,
        sales_mng_user_ids: salesMngUserId ? [salesMngUserId] : [],
        delivery_start_date: deliveryStartDate,
        delivery_end_date: deliveryEndDate,
        reg_start_date: regStartDate,
        reg_end_date: regEndDate,
        delivery_status: deliveryStatus,
        SEARCH_PART_NAME: searchPartName,
        SEARCH_PART_NO: searchPartNo,
        po_client_id: poClientId,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    } else {
      const j = await res.json().catch(() => ({}));
      Swal.fire("오류", j.message || "조회 실패", "error");
    }
  }, [
    year, customerProjectName, projectNo, unitCode, purchaseOrderNo, type,
    searchPartSpec, partnerObjid, salesMngUserId, deliveryStartDate, deliveryEndDate,
    regStartDate, regEndDate, deliveryStatus, searchPartName, searchPartNo, poClientId,
  ]);

  // 입고결과등록: 원본 가드 로직 동일
  //  - 미선택: "선택된 데이터가 없습니다."
  //  - 2건이상: "한건씩 등록 가능합니다."
  //  - MULTI_YN='Y' AND MULTI_MASTER_YN='N': "동시발주건은 마스터건으로 수입검사해야 합니다."
  const handleAcceptanceRegister = () => {
    if (selectedRows.length === 0) {
      Swal.fire("알림", "선택된 데이터가 없습니다.", "warning");
      return;
    }
    if (selectedRows.length > 1) {
      Swal.fire("알림", "한건씩 등록 가능합니다.", "warning");
      return;
    }
    const row = selectedRows[0];
    const multiYn = String(row.MULTI_YN || "");
    const multiMasterYn = String(row.MULTI_MASTER_YN || "");
    if (multiYn === "Y" && multiMasterYn === "N") {
      Swal.fire("알림", "동시발주건은 마스터건으로 수입검사해야 합니다.", "warning");
      return;
    }
    const w = 1560;
    const h = 1050;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(
      `/delivery/acceptance/form?objId=${row.OBJID}&action=regist`,
      "deliveryAcceptancePopUp",
      `width=${w},height=${h},left=${left},top=${top}`,
    );
  };

  // 부적합등록: 원본 가드 로직 동일
  //  - 미선택/복수선택 체크 + MULTI_MASTER_YN='N': "동시발주건은 마스터건으로 부적합 등록해야 합니다."
  const handleDefectRegister = () => {
    if (selectedRows.length === 0) {
      Swal.fire("알림", "선택된 데이터가 없습니다.", "warning");
      return;
    }
    if (selectedRows.length > 1) {
      Swal.fire("알림", "한건씩 등록 가능합니다.", "warning");
      return;
    }
    const row = selectedRows[0];
    const multiMasterYn = String(row.MULTI_MASTER_YN || "");
    if (multiMasterYn === "N") {
      Swal.fire("알림", "동시발주건은 마스터건으로 부적합 등록해야 합니다.", "warning");
      return;
    }
    const w = 1260;
    const h = 1050;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(
      `/delivery/defect/form?objId=${row.OBJID}`,
      "InvalidFormPopUp",
      `width=${w},height=${h},left=${left},top=${top}`,
    );
  };

  useEffect(() => {
    fetchData();
    // 최초 1회만
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  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" variant="secondary" onClick={fetchData}>조회</Button>
          <Button size="sm" onClick={handleAcceptanceRegister}>입고결과등록</Button>
          <Button size="sm" variant="secondary" onClick={handleDefectRegister}>부적합등록</Button>
        </div>
      </div>

      <SearchForm onSearch={fetchData}>
        <SearchField label="년도">
          <select
            value={year}
            onChange={(e) => setYear(e.target.value)}
            className="h-9 w-[100px] rounded border border-gray-300 bg-white px-3 text-sm"
          >
            <option value="">선택</option>
            {Array.from({ length: 5 }, (_, i) => currentYear - i).map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
        </SearchField>
        <SearchField label="프로젝트명">
          <Input value={customerProjectName} onChange={(e) => setCustomerProjectName(e.target.value)} className="w-[150px]" />
        </SearchField>
        <SearchField label="프로젝트번호">
          <Input value={projectNo} onChange={(e) => setProjectNo(e.target.value)} className="w-[140px]" placeholder="프로젝트 OBJID" />
        </SearchField>
        <SearchField label="유닛명">
          <Input value={unitCode} onChange={(e) => setUnitCode(e.target.value)} className="w-[130px]" placeholder="유닛 OBJID" />
        </SearchField>
        <SearchField label="발주No.">
          <Input value={purchaseOrderNo} onChange={(e) => setPurchaseOrderNo(e.target.value)} className="w-[120px]" />
        </SearchField>
        <SearchField label="부품구분">
          <SearchableCodeSelect codeId="0001068" value={type} onChange={setType} className="w-[130px]" />
        </SearchField>
        <SearchField label="규격">
          <Input value={searchPartSpec} onChange={(e) => setSearchPartSpec(e.target.value)} className="w-[120px]" />
        </SearchField>

        <SearchField label="공급업체">
          <SearchableSelect options={supplyOptions} value={partnerObjid} onChange={setPartnerObjid} className="w-[170px]" />
        </SearchField>
        <SearchField label="구매담당자">
          <SearchableSelect options={userOptions} value={salesMngUserId} onChange={setSalesMngUserId} className="w-[150px]" />
        </SearchField>
        <SearchField label="입고요청일">
          <div className="flex items-center gap-1">
            <input
              type="date"
              value={deliveryStartDate}
              onChange={(e) => setDeliveryStartDate(e.target.value)}
              className="h-9 rounded border border-gray-300 bg-white px-2 text-sm w-[130px]"
            />
            <span>~</span>
            <input
              type="date"
              value={deliveryEndDate}
              onChange={(e) => setDeliveryEndDate(e.target.value)}
              className="h-9 rounded border border-gray-300 bg-white px-2 text-sm w-[130px]"
            />
          </div>
        </SearchField>
        <SearchField label="발주일">
          <div className="flex items-center gap-1">
            <input
              type="date"
              value={regStartDate}
              onChange={(e) => setRegStartDate(e.target.value)}
              className="h-9 rounded border border-gray-300 bg-white px-2 text-sm w-[130px]"
            />
            <span>~</span>
            <input
              type="date"
              value={regEndDate}
              onChange={(e) => setRegEndDate(e.target.value)}
              className="h-9 rounded border border-gray-300 bg-white px-2 text-sm w-[130px]"
            />
          </div>
        </SearchField>
        <SearchField label="입고결과">
          <select
            value={deliveryStatus}
            onChange={(e) => setDeliveryStatus(e.target.value)}
            className="h-9 w-[110px] rounded border border-gray-300 bg-white px-3 text-sm"
          >
            <option value="">선택</option>
            <option value="입고중">입고중</option>
            <option value="입고완료">입고완료</option>
            <option value="지연">지연</option>
          </select>
        </SearchField>
        <SearchField label="품명">
          <Input value={searchPartName} onChange={(e) => setSearchPartName(e.target.value)} className="w-[130px]" />
        </SearchField>
        <SearchField label="품번">
          <Input value={searchPartNo} onChange={(e) => setSearchPartNo(e.target.value)} className="w-[130px]" />
        </SearchField>

        <SearchField label="발주처">
          <SearchableSelect options={supplyOptions} value={poClientId} onChange={setPoClientId} className="w-[170px]" />
        </SearchField>
      </SearchForm>

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