"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";

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

// 원본: /salesMng/salesPartChgList.do
export default function DesignChangePage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [projectNo, setProjectNo] = useState("");
  const [partNo, setPartNo] = useState("");
  const [partName, setPartName] = useState("");
  const [revision, setRevision] = useState("");
  const [changeType, setChangeType] = useState("");
  const [changeOption, setChangeOption] = useState("");
  const [partType, setPartType] = useState("");
  const [partWriter, setPartWriter] = useState("");
  const [salesWriter, setSalesWriter] = useState("");
  const [actCd, setActCd] = useState("");
  const [actStatus, setActStatus] = useState("");
  const [eoDateStart, setEoDateStart] = useState("");
  const [eoDateEnd, setEoDateEnd] = useState("");
  const [confirmDateStart, setConfirmDateStart] = useState("");
  const [confirmDateEnd, setConfirmDateEnd] = useState("");
  const [userOptions, setUserOptions] = useState<Option[]>([]);
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);

  useEffect(() => {
    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 openPartHistoryPopup = (objId: string) => {
    if (!objId) return;
    const w = 550, h = 250;
    const left = (window.screen.width - w) / 2, top = (window.screen.height - h) / 2;
    window.open(
      `/purchase/design-change/part-history?objId=${objId}`,
      "partHistory",
      `width=${w},height=${h},left=${left},top=${top}`
    );
  };

  const openOrderPopup = (pomObjId: string) => {
    if (!pomObjId) return;
    const w = 950, h = 765;
    const left = (window.screen.width - w) / 2, top = (window.screen.height - h) / 2;
    window.open(
      `/order/list/form?objId=${pomObjId}`,
      "purchaseOrderForm",
      `width=${w},height=${h},left=${left},top=${top}`
    );
  };

  const openActPopup = (row: Record<string, unknown>) => {
    const w = 600, h = 350;
    const left = (window.screen.width - w) / 2, top = (window.screen.height - h) / 2;
    const q = new URLSearchParams({
      objId: String(row.SPC_OBJID || ""),
      partObjId: String(row.OBJID || ""),
      eoNo: String(row.EO_NO || ""),
      partNo: String(row.PART_NO || ""),
      projectNo: String(row.PROJECT_NO || ""),
    }).toString();
    window.open(`/purchase/design-change/form?${q}`, "actRegist", `width=${w},height=${h},left=${left},top=${top}`);
  };

  const columns: GridColumn[] = [
    { title: "EO NO", field: "EO_NO", width: 90, hozAlign: "left" },
    { title: "프로젝트번호", field: "PROJECT_NO", width: 110, hozAlign: "left" },
    { title: "프로젝트명", field: "CUSTOMER_PROJECT_NAME", width: 160, hozAlign: "left" },
    { title: "모품번", field: "PARENT_PART_INFO", width: 130, hozAlign: "left" },
    {
      title: "품번",
      field: "PART_NO",
      width: 120,
      hozAlign: "left",
      cellClick: (row) => openPartHistoryPopup(String(row.OBJID || "")),
    },
    { title: "품명", field: "PART_NAME", width: 150, hozAlign: "left" },
    { title: "수량", field: "QTY", width: 60, hozAlign: "right" },
    { title: "변경수량", field: "QTY_TEMP", width: 80, hozAlign: "right" },
    { title: "EO구분", field: "CHANGE_TYPE_NAME", width: 90, hozAlign: "center" },
    { title: "EO사유", field: "CHANGE_OPTION_NAME", width: 90, hozAlign: "center" },
    { title: "Revision", field: "REVISION", width: 80, hozAlign: "center" },
    { title: "EO Date", field: "EO_DATE", width: 95, hozAlign: "center" },
    { title: "PART구분", field: "PART_TYPE_NAME", width: 90, hozAlign: "center" },
    { title: "설계담당자", field: "WRITER_NAME", width: 100, hozAlign: "center" },
    { title: "실행일", field: "HIS_REG_DATE_TITLE", width: 90, hozAlign: "center" },
    { title: "구매확인", field: "CONFIRM_DATE", width: 95, hozAlign: "center" },
    { title: "구매담당자", field: "WRITER1_NAME", width: 100, hozAlign: "center" },
    { title: "조치내역", field: "ACT_NAME", width: 90, hozAlign: "center" },
    {
      title: "발주서NO",
      field: "PURCHASE_ORDER_NO",
      width: 110,
      hozAlign: "left",
      cellClick: (row) => openOrderPopup(String(row.PURCHASE_ORDER_MASTER_OBJID || "")),
    },
    { title: "조치결과", field: "ACT_STATUS_NAME", width: 80, hozAlign: "center" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/purchase/design-change", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year,
        project_no: projectNo,
        part_no: partNo,
        part_name: partName,
        revision,
        change_type: changeType,
        change_option: changeOption,
        part_type: partType,
        part_writer: partWriter,
        sales_writer: salesWriter,
        act_cd: actCd,
        act_status: actStatus,
        eo_date_start: eoDateStart,
        eo_date_end: eoDateEnd,
        confirm_date_start: confirmDateStart,
        confirm_date_end: confirmDateEnd,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    } else {
      const j = await res.json().catch(() => ({}));
      Swal.fire("오류", j.message || "조회 실패", "error");
    }
  }, [
    year, projectNo, partNo, partName, revision, changeType, changeOption,
    partType, partWriter, salesWriter, actCd, actStatus,
    eoDateStart, eoDateEnd, confirmDateStart, confirmDateEnd,
  ]);

  const handleReceive = async () => {
    if (selectedRows.length === 0) {
      Swal.fire("알림", "접수할 항목을 선택하세요.", "warning");
      return;
    }
    const confirm = await Swal.fire({
      title: "접수 확인",
      text: `선택한 ${selectedRows.length}건을 접수 처리하시겠습니까?`,
      icon: "question",
      showCancelButton: true,
      confirmButtonText: "접수",
      cancelButtonText: "취소",
    });
    if (!confirm.isConfirmed) return;
    const res = await fetch("/api/purchase/design-change/receipt", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ rows: selectedRows }),
    });
    const json = await res.json();
    if (json.success) {
      Swal.fire({ icon: "success", title: json.message, timer: 1200, showConfirmButton: false });
      fetchData();
    } else {
      Swal.fire("오류", json.message || "접수 실패", "error");
    }
  };

  const handleActRegist = () => {
    if (selectedRows.length !== 1) {
      Swal.fire("알림", "조치내역을 등록할 항목 1건을 선택하세요.", "warning");
      return;
    }
    openActPopup(selectedRows[0]);
  };

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

  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={handleReceive}>
            접수
          </Button>
          <Button size="sm" variant="secondary" onClick={handleActRegist}>
            조치내역등록
          </Button>
          <Button size="sm" variant="secondary" onClick={fetchData}>
            조회
          </Button>
        </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: 5 }, (_, i) => new Date().getFullYear() - i).map((y) => (
              <option key={y} value={y}>
                {y}
              </option>
            ))}
          </select>
        </SearchField>
        <SearchField label="프로젝트번호">
          <Input value={projectNo} onChange={(e) => setProjectNo(e.target.value)} className="w-[140px]" />
        </SearchField>
        <SearchField label="품번">
          <Input value={partNo} onChange={(e) => setPartNo(e.target.value)} className="w-[120px]" />
        </SearchField>
        <SearchField label="품명">
          <Input value={partName} onChange={(e) => setPartName(e.target.value)} className="w-[120px]" />
        </SearchField>
        <SearchField label="Revision">
          <Input value={revision} onChange={(e) => setRevision(e.target.value)} className="w-[80px]" />
        </SearchField>
        <SearchField label="EO구분">
          <SearchableCodeSelect codeId="0001054" value={changeType} onChange={setChangeType} className="w-[130px]" />
        </SearchField>
        <SearchField label="EO사유">
          <SearchableCodeSelect codeId="0000318" value={changeOption} onChange={setChangeOption} className="w-[130px]" />
        </SearchField>
        <SearchField label="PART구분">
          <SearchableCodeSelect codeId="0000062" value={partType} onChange={setPartType} className="w-[130px]" />
        </SearchField>
        <SearchField label="설계담당자">
          <SearchableSelect options={userOptions} value={partWriter} onChange={setPartWriter} className="w-[130px]" />
        </SearchField>
        <SearchField label="구매담당자">
          <SearchableSelect options={userOptions} value={salesWriter} onChange={setSalesWriter} className="w-[130px]" />
        </SearchField>
        <SearchField label="조치내역">
          <SearchableCodeSelect codeId="0001059" value={actCd} onChange={setActCd} className="w-[130px]" />
        </SearchField>
        <SearchField label="조치결과">
          <SearchableCodeSelect codeId="0001062" value={actStatus} onChange={setActStatus} className="w-[130px]" />
        </SearchField>
        <SearchField label="EO Date">
          <div className="flex items-center gap-1">
            <input
              type="date"
              value={eoDateStart}
              onChange={(e) => setEoDateStart(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={eoDateEnd}
              onChange={(e) => setEoDateEnd(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={confirmDateStart}
              onChange={(e) => setConfirmDateStart(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={confirmDateEnd}
              onChange={(e) => setConfirmDateEnd(e.target.value)}
              className="h-9 rounded border border-gray-300 bg-white px-2 text-sm w-[130px]"
            />
          </div>
        </SearchField>
      </SearchForm>

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

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