"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 { SearchableCodeSelect } from "@/components/ui/searchable-code-select";
import { SearchableSelect } from "@/components/ui/searchable-select";
import Swal from "sweetalert2";
import { ApprovalButton } from "@/components/approval/ApprovalButton";

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

// 원본: /purchaseOrder/purchaseOrderList_new.do
export default function OrderListPage() {
  const [year, setYear] = useState("");
  const [customerCd, setCustomerCd] = useState("");
  const [projectNo, setProjectNo] = useState("");
  const [unitCode, setUnitCode] = useState("");
  const [purchaseOrderNo, setPurchaseOrderNo] = useState("");
  const [type, setType] = useState("");
  const [orderTypeCd, setOrderTypeCd] = useState("");
  const [deliveryStartDate, setDeliveryStartDate] = useState("");
  const [deliveryEndDate, setDeliveryEndDate] = useState("");
  const [partnerObjid, setPartnerObjid] = useState("");
  const [salesMngUserId, setSalesMngUserId] = useState("");
  const [regStartDate, setRegStartDate] = useState("");
  const [regEndDate, setRegEndDate] = useState("");
  const [partNo, setPartNo] = useState("");
  const [partName, setPartName] = useState("");
  const [poClientId, setPoClientId] = useState("");
  const [apprStatus, setApprStatus] = useState("");
  const [partSpec, setPartSpec] = useState("");

  const [customerOptions, setCustomerOptions] = useState<Option[]>([]);
  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/common/supply-list", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })
      .then((r) => r.json())
      .then((d) =>
        setCustomerOptions(
          (d.RESULTLIST || []).map((r: Record<string, unknown>) => ({
            value: String(r.OBJID),
            label: String(r.SUPPLY_NAME),
          })),
        ),
      )
      .catch(() => {});

    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 url = objId ? `/order/list/form?objId=${objId}&action=view` : "/order/list/form";
    const w = 1460;
    const h = 1050;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(url, `orderForm_${objId || "new"}`, `width=${w},height=${h},left=${left},top=${top}`);
  };

  const columns: GridColumn[] = [
    {
      title: "발주No",
      field: "PURCHASE_ORDER_NO",
      width: 130,
      hozAlign: "left",
      frozen: true,
      cellClick: (row) => openOrderForm(String(row.OBJID || "")),
    },
    { title: "년도", field: "CM_YEAR", width: 60, hozAlign: "center" },
    { title: "고객사", field: "CUSTOMER_NAME", width: 130, hozAlign: "left" },
    { title: "고객사프로젝트명", field: "CUSTOMER_PROJECT_NAME", width: 180, hozAlign: "left" },
    { title: "당사프로젝트번호", field: "PROJECT_NO", width: 130, hozAlign: "left" },
    { title: "부품", field: "TYPE_NAME", width: 70, hozAlign: "center" },
    { title: "구분", field: "ORDER_TYPE_CD_NAME", width: 70, hozAlign: "center" },
    { title: "동시", field: "MULTI_YN_MAKED", width: 50, hozAlign: "center" },
    { title: "발주서제목", field: "TITLE", width: 220, hozAlign: "left" },
    { title: "납품장소", field: "DELIVERY_PLACE_NAME", width: 100, hozAlign: "center" },
    { title: "검수방법", field: "INSPECT_METHOD_NAME", width: 90, hozAlign: "center" },
    { title: "결재조건", field: "PAYMENT_TERMS_NAME", width: 110, hozAlign: "center" },
    { title: "입고요청일", field: "DELIVERY_DATE", width: 100, hozAlign: "center" },
    { title: "공급업체", field: "PARTNER_NAME", width: 140, hozAlign: "left" },
    { title: "구매담당", field: "SALES_MNG_USER_NAME", width: 80, hozAlign: "center" },
    { title: "발주일", field: "REGDATE", width: 100, hozAlign: "center" },
    { title: "발주금액", field: "TOTAL_PRICE_ALL", width: 110, hozAlign: "right", formatter: "money" },
    { title: "상태", field: "APPR_STATUS_NAME", width: 80, hozAlign: "center" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/order/list", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year,
        customer_cd: customerCd,
        project_no: projectNo,
        unit_code: unitCode,
        purchase_order_no: purchaseOrderNo,
        type,
        order_type_cd: orderTypeCd,
        delivery_start_date: deliveryStartDate,
        delivery_end_date: deliveryEndDate,
        partner_objid: partnerObjid,
        sales_mng_user_id: salesMngUserId,
        reg_start_date: regStartDate,
        reg_end_date: regEndDate,
        part_no: partNo,
        part_name: partName,
        po_client_id: poClientId,
        appr_status: apprStatus,
        part_spec: partSpec,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    } else {
      const j = await res.json().catch(() => ({}));
      Swal.fire("오류", j.message || "조회 실패", "error");
    }
  }, [
    year, customerCd, projectNo, unitCode, purchaseOrderNo, type, orderTypeCd,
    deliveryStartDate, deliveryEndDate, partnerObjid, salesMngUserId,
    regStartDate, regEndDate, partNo, partName, poClientId, apprStatus, partSpec,
  ]);

  const masterSelectedIds = selectedRows
    .filter((r) => r.MULTI_YN !== "Y" || r.MULTI_MASTER_YN === "Y")
    .map((r) => String(r.OBJID));

  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" onClick={() => openOrderForm()}>발주서작성</Button>
          <Button size="sm" variant="secondary" onClick={fetchData}>조회</Button>
          <ApprovalButton
            objIds={masterSelectedIds}
            targetType="PURCHASE_ORDER"
            title={`발주 결재 요청 (${masterSelectedIds.length}건)`}
            description={selectedRows.map((r) => `${r.PURCHASE_ORDER_NO} - ${r.TITLE}`).join("\n")}
            onSuccess={fetchData}
            disabled={masterSelectedIds.length === 0}
          />
        </div>
      </div>

      <SearchForm onSearch={fetchData}>
        <SearchField label="년도">
          <select
            value={year}
            onChange={(e) => setYear(e.target.value)}
            className="h-9 w-[90px] rounded border border-gray-300 bg-white px-3 text-sm"
          >
            <option value="">전체</option>
            {Array.from({ length: 6 }, (_, i) => new Date().getFullYear() - i).map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
        </SearchField>
        <SearchField label="고객사">
          <SearchableSelect options={customerOptions} value={customerCd} onChange={setCustomerCd} className="w-[160px]" />
        </SearchField>
        <SearchField label="프로젝트번호">
          <Input value={projectNo} onChange={(e) => setProjectNo(e.target.value)} className="w-[150px]" />
        </SearchField>
        <SearchField label="유닛">
          <Input value={unitCode} onChange={(e) => setUnitCode(e.target.value)} className="w-[130px]" placeholder="유닛코드" />
        </SearchField>
        <SearchField label="발주No">
          <Input value={purchaseOrderNo} onChange={(e) => setPurchaseOrderNo(e.target.value)} className="w-[140px]" />
        </SearchField>
        <SearchField label="발주부품">
          <SearchableCodeSelect codeId="0001068" value={type} onChange={setType} className="w-[130px]" />
        </SearchField>
        <SearchField label="발주구분">
          <SearchableCodeSelect codeId="0001406" value={orderTypeCd} onChange={setOrderTypeCd} className="w-[130px]" />
        </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="공급업체">
          <SearchableSelect options={supplyOptions} value={partnerObjid} onChange={setPartnerObjid} className="w-[160px]" />
        </SearchField>
        <SearchField label="구매담당">
          <SearchableSelect options={userOptions} value={salesMngUserId} onChange={setSalesMngUserId} className="w-[130px]" />
        </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="품번">
          <Input value={partNo} onChange={(e) => setPartNo(e.target.value)} className="w-[130px]" />
        </SearchField>
        <SearchField label="품명">
          <Input value={partName} onChange={(e) => setPartName(e.target.value)} className="w-[130px]" />
        </SearchField>
        <SearchField label="발주처">
          <SearchableSelect options={supplyOptions} value={poClientId} onChange={setPoClientId} className="w-[160px]" />
        </SearchField>
        <SearchField label="상태">
          <select
            value={apprStatus}
            onChange={(e) => setApprStatus(e.target.value)}
            className="h-9 w-[120px] rounded border border-gray-300 bg-white px-3 text-sm"
          >
            <option value="">전체</option>
            <option value="create">작성중</option>
            <option value="inProcess">결재중</option>
            <option value="reject">반려</option>
            <option value="complete">결재완료</option>
            <option value="cancel">취소</option>
          </select>
        </SearchField>
        <SearchField label="규격">
          <Input value={partSpec} onChange={(e) => setPartSpec(e.target.value)} className="w-[130px]" />
        </SearchField>
      </SearchForm>

      <DataGrid
        columns={columns}
        data={data}
        showCheckbox

        onSelectionChange={setSelectedRows}
      />
    </div>
  );
}
