"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/salesLongDeliveryList.do
export default function StockPage() {
  const [ldPartName, setLdPartName] = useState("");
  const [spec, setSpec] = useState("");
  const [location, setLocation] = useState("");
  const [maker, setMaker] = useState("");
  const [materialCode, setMaterialCode] = useState("");
  const [adminSupply, setAdminSupply] = useState("");
  const [supplyOptions, setSupplyOptions] = 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(() => {});
  }, []);

  const openStandardPopup = (objId?: string) => {
    const w = 600, h = 300;
    const left = (window.screen.width - w) / 2, top = (window.screen.height - h) / 2;
    window.open(
      `/purchase/stock/form?actionType=STANDARD${objId ? `&objId=${objId}` : ""}`,
      "stockStandard",
      `width=${w},height=${h},left=${left},top=${top}`
    );
  };

  const openInputPopup = (objId: string) => {
    if (!objId) return;
    const w = 600, h = 590;
    const left = (window.screen.width - w) / 2, top = (window.screen.height - h) / 2;
    window.open(
      `/purchase/stock/form?actionType=INPUT&objId=${objId}`,
      "stockInput",
      `width=${w},height=${h},left=${left},top=${top}`
    );
  };

  const openPredictPopup = (objId: string) => {
    if (!objId) return;
    const w = 900, h = 590;
    const left = (window.screen.width - w) / 2, top = (window.screen.height - h) / 2;
    window.open(
      `/purchase/stock/form?actionType=PREDICT&objId=${objId}`,
      "stockPredict",
      `width=${w},height=${h},left=${left},top=${top}`
    );
  };

  const columns: GridColumn[] = [
    {
      title: "품명",
      field: "LD_PART_NAME",
      width: 180,
      hozAlign: "left",
      cellClick: (row) => openStandardPopup(String(row.OBJID || "")),
    },
    { title: "사양(규격)", field: "SPEC", width: 300, hozAlign: "left" },
    { title: "Location", field: "LOCATION_NAME", width: 100, hozAlign: "center" },
    { title: "내자/외자", field: "FORM_NO", width: 100, hozAlign: "center" },
    { title: "메이커", field: "MAKER", width: 100, hozAlign: "left" },
    { title: "자재코드", field: "MATERIAL_CODE", width: 160, hozAlign: "left" },
    { title: "공급업체", field: "SUPPLY_NAME", width: 140, hozAlign: "left" },
    { title: "재고수량", field: "INPUT_QTY", width: 85, hozAlign: "right", formatter: "money" },
    {
      title: "자재투입이력",
      field: "INPUT_CNT",
      width: 100,
      hozAlign: "right",
      formatter: "money",
      cellClick: (row) => openInputPopup(String(row.OBJID || "")),
    },
    { title: "단가", field: "PRICE", width: 90, hozAlign: "right", formatter: "money" },
    { title: "보유금액", field: "PRICE_SUM", width: 120, hozAlign: "right", formatter: "money" },
    { title: "합계", field: "M_TOTAL", width: 80, hozAlign: "right", formatter: "money" },
    { title: "1월", field: "M01", width: 60, hozAlign: "right", formatter: "money" },
    { title: "2월", field: "M02", width: 60, hozAlign: "right", formatter: "money" },
    { title: "3월", field: "M03", width: 60, hozAlign: "right", formatter: "money" },
    { title: "4월", field: "M04", width: 60, hozAlign: "right", formatter: "money" },
    { title: "5월", field: "M05", width: 60, hozAlign: "right", formatter: "money" },
    { title: "6월", field: "M06", width: 60, hozAlign: "right", formatter: "money" },
    { title: "7월", field: "M07", width: 60, hozAlign: "right", formatter: "money" },
    { title: "8월", field: "M08", width: 60, hozAlign: "right", formatter: "money" },
    { title: "9월", field: "M09", width: 60, hozAlign: "right", formatter: "money" },
    { title: "10월", field: "M10", width: 60, hozAlign: "right", formatter: "money" },
    { title: "11월", field: "M11", width: 60, hozAlign: "right", formatter: "money" },
    { title: "12월", field: "M12", width: 60, hozAlign: "right", formatter: "money" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/purchase/stock", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        ld_part_name: ldPartName,
        spec,
        Location: location,
        maker,
        material_code: materialCode,
        admin_supply: adminSupply,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    } else {
      const j = await res.json().catch(() => ({}));
      Swal.fire("오류", j.message || "조회 실패", "error");
    }
  }, [ldPartName, spec, location, maker, materialCode, adminSupply]);

  const totalCost = data.reduce((sum, r) => sum + Number(r.PRICE_SUM || 0), 0);

  const handleDelete = 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/stock/delete", {
      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 handleInputClick = () => {
    if (selectedRows.length !== 1) {
      Swal.fire("알림", "자재투입할 항목 1건을 선택하세요.", "warning");
      return;
    }
    openInputPopup(String(selectedRows[0].OBJID || ""));
  };
  const handlePredictClick = () => {
    if (selectedRows.length !== 1) {
      Swal.fire("알림", "예측수량을 등록할 항목 1건을 선택하세요.", "warning");
      return;
    }
    openPredictPopup(String(selectedRows[0].OBJID || ""));
  };

  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" variant="secondary" onClick={fetchData}>조회</Button>
          <Button size="sm" variant="danger" onClick={handleDelete}>삭제</Button>
          <Button size="sm" onClick={() => openStandardPopup()}>등록</Button>
          <Button size="sm" variant="secondary" onClick={handleInputClick}>자재투입</Button>
          <Button size="sm" variant="secondary" onClick={handlePredictClick}>예측수량등록</Button>
        </div>
      </div>

      <SearchForm onSearch={fetchData}>
        <SearchField label="품명">
          <Input value={ldPartName} onChange={(e) => setLdPartName(e.target.value)} className="w-[160px]" />
        </SearchField>
        <SearchField label="사양(규격)">
          <Input value={spec} onChange={(e) => setSpec(e.target.value)} className="w-[160px]" />
        </SearchField>
        <SearchField label="Location">
          <SearchableCodeSelect codeId="0000262" value={location} onChange={setLocation} className="w-[140px]" />
        </SearchField>
        <SearchField label="메이커">
          <Input value={maker} onChange={(e) => setMaker(e.target.value)} className="w-[140px]" />
        </SearchField>
        <SearchField label="자재코드">
          <Input value={materialCode} onChange={(e) => setMaterialCode(e.target.value)} className="w-[140px]" />
        </SearchField>
        <SearchField label="공급업체">
          <SearchableSelect
            options={supplyOptions}
            value={adminSupply}
            onChange={setAdminSupply}
            className="w-[180px]"
            placeholder="전체"
          />
        </SearchField>
      </SearchForm>

      <div className="flex items-center gap-6 mb-3 text-sm font-bold text-red-600">
        <span>장납기품 비용(원) : {totalCost.toLocaleString()}</span>
      </div>

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