"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/salesRequestMngRegList.do
export default function PurchaseRequestPage() {
  const [year, setYear] = useState("");
  const [projectNo, setProjectNo] = useState("");
  const [requestCd, setRequestCd] = useState("");
  const [receiptWriter, setReceiptWriter] = useState("");
  const [status, setStatus] = useState("");
  const [receiptDateStart, setReceiptDateStart] = useState("");
  const [receiptDateEnd, setReceiptDateEnd] = 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 openRequestForm = (objId?: string) => {
    const url = objId ? `/purchase/request/form?objId=${objId}` : "/purchase/request/form";
    const w = 1100, h = 630;
    const left = (window.screen.width - w) / 2, top = (window.screen.height - h) / 2;
    window.open(url, "requestForm", `width=${w},height=${h},left=${left},top=${top}`);
  };

  const columns: GridColumn[] = [
    {
      title: "요청번호",
      field: "REQUEST_MNG_NO",
      width: 110,
      hozAlign: "left",
      cellClick: (row) => openRequestForm(String(row.OBJID || "")),
    },
    { title: "요청구분", field: "REQUEST_CD_NAME", width: 80, hozAlign: "center" },
    { title: "프로젝트번호", field: "PROJECT_NUMBER", width: 110, hozAlign: "left" },
    { title: "프로젝트명", field: "PROJECT_NAME", width: 150, hozAlign: "left" },
    { title: "유닛명", field: "UNIT_CODE_NAME", width: 170, hozAlign: "left" },
    { title: "구매요청품 수", field: "ITEMS_QTY", width: 110, hozAlign: "right", formatter: "money" },
    { title: "총 수량", field: "TOTAL_QTY", width: 90, hozAlign: "right", formatter: "money" },
    { title: "요청사유", field: "REQUEST_REASONS_NAME", width: 100, hozAlign: "left" },
    { title: "요청인", field: "REQUEST_USER_NAME", width: 110, hozAlign: "center" },
    { title: "입고요청일", field: "DELIVERY_REQUEST_DATE", width: 100, hozAlign: "center" },
    { title: "상태", field: "STATUS_TITLE", width: 90, hozAlign: "center" },
    { title: "접수자", field: "RECEIPT_USER_NAME", width: 100, hozAlign: "center" },
    { title: "접수일", field: "RECEIPT_DATE", width: 90, hozAlign: "center" },
    { title: "발주서NO", field: "PURCHASE_ORDER_NO_ARR", width: 180, hozAlign: "left" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/purchase/request", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year,
        project_no: projectNo,
        request_cd: requestCd,
        receipt_writer: receiptWriter,
        status,
        receipt_date_start: receiptDateStart,
        receipt_date_end: receiptDateEnd,
      }),
    });
    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, requestCd, receiptWriter, status, receiptDateStart, receiptDateEnd]);

  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/request/receipt", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ objIds: selectedRows.map((r) => String(r.OBJID)) }),
    });
    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 handleOrderWrite = () => {
    Swal.fire("알림", "발주서작성 기능은 준비 중입니다.", "info");
  };

  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={() => openRequestForm()}>
            구매요청서작성
          </Button>
          <Button size="sm" variant="secondary" onClick={handleOrderWrite}>
            발주서작성
          </Button>
          <Button size="sm" variant="secondary" onClick={handleReceive}>
            접수
          </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="요청구분">
          <SearchableCodeSelect codeId="0000167" value={requestCd} onChange={setRequestCd} className="w-[140px]" />
        </SearchField>
        <SearchField label="상태">
          <select
            value={status}
            onChange={(e) => setStatus(e.target.value)}
            className="h-9 w-[130px] rounded border border-gray-300 bg-white px-3 text-sm"
          >
            <option value="">전체</option>
            <option value="create">등록</option>
            <option value="release">제출 완료</option>
            <option value="reception">접수</option>
            <option value="approvalRequest">결재중</option>
            <option value="approvalComplete">결재완료</option>
            <option value="reject">반려</option>
          </select>
        </SearchField>
        <SearchField label="접수자">
          <SearchableSelect
            options={userOptions}
            value={receiptWriter}
            onChange={setReceiptWriter}
            className="w-[140px]"
          />
        </SearchField>
        <SearchField label="접수일">
          <div className="flex items-center gap-1">
            <input
              type="date"
              value={receiptDateStart}
              onChange={(e) => setReceiptDateStart(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={receiptDateEnd}
              onChange={(e) => setReceiptDateEnd(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>
  );
}
