"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 { CodeSelect } from "@/components/ui/code-select";
import Swal from "sweetalert2";

// 입고관리 > 단가관리
export default function PricePage() {
  const [partnerObjid, setPartnerObjid] = useState("");
  const [partName, setPartName] = useState("");
  const [partNo, setPartNo] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "공급업체", field: "PARTNER_NAME", width: 180, hozAlign: "left" },
    { title: "Part No", field: "PART_NO", width: 120, hozAlign: "left" },
    { title: "품명", field: "PART_NAME", width: 150, hozAlign: "left" },
    { title: "규격", field: "SPEC", width: 150, hozAlign: "left" },
    { title: "재질", field: "MATERIAL", width: 100, hozAlign: "left" },
    { title: "단위", field: "UNIT_NAME", width: 60, hozAlign: "center" },
    { title: "단가", field: "UNIT_PRICE", width: 100, hozAlign: "right", formatter: "money" },
    { title: "적용시작일", field: "START_DATE", width: 100, hozAlign: "center" },
    { title: "적용종료일", field: "END_DATE", width: 100, hozAlign: "center" },
    { title: "등록일", field: "REG_DATE", width: 100, hozAlign: "center" },
    { title: "비고", field: "REMARK", width: 200, hozAlign: "left" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/delivery/price", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        partner_objid: partnerObjid,
        part_name: partName,
        part_no: partNo,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [partnerObjid, partName, partNo]);

  const handleDelete = async () => {
    if (selectedRows.length === 0) {
      Swal.fire("알림", "삭제할 항목을 선택하세요.", "warning");
      return;
    }
    const result = await Swal.fire({
      title: "삭제 확인",
      text: `선택한 ${selectedRows.length}건을 삭제하시겠습니까?`,
      icon: "question",
      showCancelButton: true,
      confirmButtonText: "삭제",
      cancelButtonText: "취소",
    });
    if (result.isConfirmed) {
      Swal.fire("완료", "삭제되었습니다.", "success");
      fetchData();
    }
  };

  const handleExcelDownload = () => {
    Swal.fire("알림", "Excel 다운로드 기능은 준비 중입니다.", "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={() => {/* TODO: open register form */}}>등록</Button>
          <Button size="sm" variant="danger" onClick={handleDelete}>삭제</Button>
          <Button size="sm" variant="secondary" onClick={fetchData}>조회</Button>
          <Button size="sm" variant="secondary" onClick={handleExcelDownload}>Excel Download</Button>
        </div>
      </div>

      <SearchForm onSearch={fetchData}>
        <SearchField label="공급업체">
          <CodeSelect codeId="PARTNER" value={partnerObjid} onChange={setPartnerObjid} className="w-[160px]" />
        </SearchField>
        <SearchField label="Part No">
          <Input value={partNo} onChange={(e) => setPartNo(e.target.value)} placeholder="Part No" className="w-[150px]" />
        </SearchField>
        <SearchField label="품명">
          <Input value={partName} onChange={(e) => setPartName(e.target.value)} placeholder="품명" className="w-[150px]" />
        </SearchField>
      </SearchForm>

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

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