"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 { FolderCell } from "@/components/ui/folder-cell";
import Swal from "sweetalert2";

// 영업관리 > 계약관리 (원본: contractMgmt/contractList.jsp)
export default function ContractPage() {
  const currentYear = new Date().getFullYear();
  const [year, setYear] = useState(String(currentYear));
  const [categoryCd, setCategoryCd] = useState("");
  const [customerObjid, setCustomerObjid] = useState("");
  const [product, setProduct] = useState("");
  const [contractResult, setContractResult] = useState("");
  const [pmUserId, setPmUserId] = useState("");
  const [contractStartDate, setContractStartDate] = useState("");
  const [contractEndDate, setContractEndDate] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);
  const [customers, setCustomers] = useState<{ value: string; label: string }[]>([]);
  const [pmUsers, setPmUsers] = useState<{ value: string; label: string }[]>([]);

  useEffect(() => {
    fetch("/api/sales/customer", {
      method: "POST", headers: { "Content-Type": "application/json" }, body: "{}",
    }).then((r) => r.json()).then((d) => {
      setCustomers((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) => {
      setPmUsers((d.RESULTLIST || []).map((r: Record<string, unknown>) => ({
        value: String(r.USER_ID), label: String(r.USER_NAME || ""),
      })));
    }).catch(() => {});
  }, []);

  const openContractForm = (objId?: string) => {
    const url = objId ? `/sales/contract/form?objId=${objId}` : "/sales/contract/form?actionType=regist";
    const w = 1280, h = 780;
    const left = Math.max(0, (window.screen.width - w) / 2);
    const top = Math.max(0, (window.screen.availHeight - h) / 2);
    window.open(url, "contractForm", `width=${w},height=${h},left=${left},top=${top}`);
  };

  // 그리드 컬럼 — 원본 3개 섹션(영업정보/진행사항/수주정보) 순서대로 플랫하게 배치
  const columns: GridColumn[] = [
    // ----- 영업번호 (frozen) -----
    {
      title: "영업번호", field: "CONTRACT_NO", width: 100, frozen: true,
      cellClick: (row) => openContractForm(String(row.OBJID || "")),
    },
    // ----- 영업정보(상세) -----
    { title: "계약구분", field: "CATEGORY_NAME", width: 80 },
    { title: "차수", field: "OVERHAUL_ORDER", width: 60, hozAlign: "right" },
    { title: "국내/해외", field: "AREA_NAME", width: 80 },
    { title: "고객사", field: "CUSTOMER_NAME", width: 160 },
    { title: "제품구분", field: "PRODUCT_NAME", width: 90 },
    { title: "기계형식", field: "MECHANICAL_TYPE", width: 110 },
    { title: "고객사 프로젝트명", field: "CUSTOMER_PROJECT_NAME", width: 200 },
    { title: "예상납기일", field: "DUE_DATE", width: 100, hozAlign: "center" },
    { title: "입고지", field: "LOCATION", width: 100 },
    { title: "셋업지", field: "SETUP", width: 100 },
    { title: "설비방향", field: "FACILITY_NAME", width: 90 },
    { title: "설비대수", field: "FACILITY_QTY", width: 75, formatter: "money", hozAlign: "right" },
    { title: "설비타입", field: "FACILITY_TYPE", width: 100 },
    { title: "설비길이", field: "FACILITY_DEPTH", width: 90 },
    { title: "담당자", field: "WRITER_NAME", width: 80 },
    { title: "등록일", field: "REG_DATE", width: 100, hozAlign: "center" },
    {
      title: "첨부", field: "CU01_CNT", width: 60, hozAlign: "center",
      formatter: (_c, row) => (
        <FolderCell
          count={row.CU01_CNT}
          onClick={
            Number(row.CU01_CNT) > 0
              ? () => window.open(`/common/files?objId=${row.OBJID}&docType=contractMgmt01`, "files", "width=800,height=500")
              : undefined
          }
        />
      ),
    },
    // ----- 진행사항 -----
    {
      title: "검토", field: "CU03_CNT", width: 60, hozAlign: "right",
      formatter: (_c, row) => Number(row.CU03_CNT || 0) > 0 ? String(row.CU03_CNT) : "",
    },
    { title: "상태", field: "CONTRACT_RESULT_NAME", width: 80 },
    // ----- 수주정보 -----
    { title: "수주일", field: "CONTRACT_DATE", width: 100, hozAlign: "center" },
    { title: "PO계약 No", field: "PO_NO", width: 110 },
    { title: "PM", field: "PM_USER_NAME", width: 80 },
    { title: "통화", field: "CONTRACT_CURRENCY_NAME", width: 70 },
    { title: "수주가", field: "CONTRACT_PRICE_CURRENCY", width: 110, formatter: "money", hozAlign: "right" },
    { title: "당사프로젝트명", field: "PROJECT_NAME", width: 180 },
    { title: "계약납기일", field: "CONTRACT_DEL_DATE", width: 100, hozAlign: "center" },
    { title: "요청납기일", field: "REQ_DEL_DATE", width: 100, hozAlign: "center" },
    { title: "수주회사", field: "CONTRACT_COMPANY_NAME", width: 90 },
    { title: "제작공장", field: "MANUFACTURE_PLANT_NAME", width: 90 },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/sales/contract", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        Year: year,
        category_cd: categoryCd,
        customer_objid: customerObjid,
        product,
        contract_result: contractResult,
        pm_user_id: pmUserId,
        contract_start_date: contractStartDate,
        contract_end_date: contractEndDate,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [year, categoryCd, customerObjid, product, contractResult, pmUserId, contractStartDate, contractEndDate]);

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

  const handleDelete = async () => {
    if (selectedRows.length === 0) {
      Swal.fire("알림", "선택한 항목이 없습니다.", "warning");
      return;
    }
    const r = await Swal.fire({
      title: "선택한 계약을 삭제하시겠습니까?",
      icon: "warning", showCancelButton: true,
      confirmButtonText: "확인", cancelButtonText: "취소",
    });
    if (!r.isConfirmed) return;
    const res = await fetch("/api/sales/contract/delete", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ objIds: selectedRows.map((row) => String(row.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");
    }
  };

  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="danger" onClick={handleDelete}>삭제</Button>
          <Button size="sm" onClick={() => openContractForm()}>등록</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-[100px] rounded border border-gray-300 bg-white px-2 text-sm">
            <option value="">전체</option>
            {Array.from({ length: 5 }, (_, i) => currentYear - i).map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
        </SearchField>
        <SearchField label="계약구분">
          <SearchableCodeSelect codeId="0000167" value={categoryCd} onChange={setCategoryCd} className="w-[140px]" />
        </SearchField>
        <SearchField label="고객사">
          <select value={customerObjid} onChange={(e) => setCustomerObjid(e.target.value)}
            className="h-9 w-[160px] rounded border border-gray-300 bg-white px-2 text-sm">
            <option value="">전체</option>
            {customers.map((c) => <option key={c.value} value={c.value}>{c.label}</option>)}
          </select>
        </SearchField>
        <SearchField label="제품구분">
          <SearchableCodeSelect codeId="0000001" value={product} onChange={setProduct} className="w-[130px]" />
        </SearchField>
        <SearchField label="계약일">
          <div className="flex items-center gap-1">
            <Input type="date" value={contractStartDate} onChange={(e) => setContractStartDate(e.target.value)} className="w-[140px]" />
            <span className="text-xs text-gray-500">~</span>
            <Input type="date" value={contractEndDate} onChange={(e) => setContractEndDate(e.target.value)} className="w-[140px]" />
          </div>
        </SearchField>
        <SearchField label="수주결과">
          <SearchableCodeSelect codeId="0000963" value={contractResult} onChange={setContractResult} className="w-[130px]" />
        </SearchField>
        <SearchField label="PM">
          <select value={pmUserId} onChange={(e) => setPmUserId(e.target.value)}
            className="h-9 w-[140px] rounded border border-gray-300 bg-white px-2 text-sm">
            <option value="">전체</option>
            {pmUsers.map((u) => <option key={u.value} value={u.value}>{u.label}</option>)}
          </select>
        </SearchField>
      </SearchForm>

      <div className="text-xs text-gray-500 mb-2">총 {data.length}건</div>

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

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