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

// 영업관리 > 출고관리 (원본: releaseMgmt/releaseMgmtList.jsp)
export default function ReleasePage() {
  const currentYear = new Date().getFullYear();
  const [year, setYear] = useState(String(currentYear));
  const [categoryCd, setCategoryCd] = useState("");
  const [customerObjid, setCustomerObjid] = useState("");
  const [product, setProduct] = useState("");
  const [pmUserId, setPmUserId] = useState("");
  const [releaseStartDate, setReleaseStartDate] = useState("");
  const [releaseEndDate, setReleaseEndDate] = useState("");
  const [installResult, setInstallResult] = 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 openForm = (row: Record<string, unknown>) => {
    const projectObjId = String(row.OBJID || "");
    if (!projectObjId) return;
    const w = 900, h = 760;
    const left = Math.max(0, (window.screen.width - w) / 2);
    const top = Math.max(0, (window.screen.availHeight - h) / 2);
    window.open(`/sales/release/form?projectObjId=${projectObjId}`, "releaseForm", `width=${w},height=${h},left=${left},top=${top}`);
  };

  const columns: GridColumn[] = [
    {
      title: "프로젝트번호", field: "PROJECT_NO", width: 120, frozen: true,
      cellClick: (row) => openForm(row),
    },
    // 프로젝트정보
    { 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: 100 },
    { title: "당사프로젝트명", field: "PROJECT_NAME", width: 180 },
    { title: "요청납기일", field: "REQ_DEL_DATE", width: 100, hozAlign: "center" },
    { title: "입고지", field: "LOCATION", width: 90 },
    { title: "셋업지", field: "SETUP", width: 90 },
    { title: "설비방향", field: "FACILITY_NAME", width: 80 },
    { title: "설비대수", field: "FACILITY_QTY", width: 70, formatter: "money", hozAlign: "right" },
    { title: "설비타입", field: "FACILITY_TYPE", width: 90 },
    { title: "설비길이", field: "FACILITY_DEPTH", width: 80 },
    { title: "PM", field: "PM_USER_NAME", width: 80 },
    { title: "계약납기일", field: "CONTRACT_DEL_DATE", width: 100, hozAlign: "center" },
    // 출고정보
    {
      title: "출고검사", field: "RELEASE_CHECK_CNT", width: 75, hozAlign: "center",
      formatter: (_c, row) => (
        <FolderCell
          count={row.RELEASE_CHECK_CNT}
          onClick={
            Number(row.RELEASE_CHECK_CNT) > 0
              ? () => window.open(`/common/files?objId=${row.OBJID}&docType=RELEASE_CHECK`, "files", "width=800,height=500")
              : undefined
          }
        />
      ),
    },
    {
      title: "출하지시", field: "RELEASE_ORDER_CNT", width: 75, hozAlign: "center",
      formatter: (_c, row) => (
        <FolderCell
          count={row.RELEASE_ORDER_CNT}
          onClick={
            Number(row.RELEASE_ORDER_CNT) > 0
              ? () => window.open(`/common/files?objId=${row.OBJID}&docType=RELEASE_ORDER`, "files", "width=800,height=500")
              : undefined
          }
        />
      ),
    },
    { title: "출고일", field: "RELEASE_DATE", width: 100, hozAlign: "center" },
    { title: "출고결과", field: "RELEASE_STATUS_TITLE", width: 80 },
    // 설치&시운전
    { title: "설치완료일", field: "INSTALL_COMPLETE_DATE", width: 100, hozAlign: "center" },
    { title: "설치결과", field: "INSTALL_RESULT", width: 80 },
    {
      title: "인수인계", field: "RELEASE_TAKING_OVER_CNT", width: 80, hozAlign: "center",
      formatter: (_c, row) => (
        <FolderCell
          count={row.RELEASE_TAKING_OVER_CNT}
          onClick={
            Number(row.RELEASE_TAKING_OVER_CNT) > 0
              ? () => window.open(`/common/files?objId=${row.OBJID}&docType=RELEASE_TAKING_OVER`, "files", "width=800,height=500")
              : undefined
          }
        />
      ),
    },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/sales/release", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        Year: year,
        category_cd: categoryCd,
        customer_objid: customerObjid,
        product,
        pm_user_id: pmUserId,
        release_start_date: releaseStartDate,
        release_end_date: releaseEndDate,
        install_result: installResult,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [year, categoryCd, customerObjid, product, pmUserId, releaseStartDate, releaseEndDate, installResult]);

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

  const handleRegister = () => {
    if (selectedRows.length === 0) {
      Swal.fire("알림", "선택된 내용이 없습니다.", "warning");
      return;
    }
    if (selectedRows.length > 1) {
      Swal.fire("알림", "한번에 1개의 내용만 등록 가능합니다.", "warning");
      return;
    }
    openForm(selectedRows[0]);
  };

  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={handleRegister}>등록</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-[180px] 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={releaseStartDate} onChange={(e) => setReleaseStartDate(e.target.value)} className="w-[140px]" />
            <span className="text-xs text-gray-500">~</span>
            <Input type="date" value={releaseEndDate} onChange={(e) => setReleaseEndDate(e.target.value)} className="w-[140px]" />
          </div>
        </SearchField>
        <SearchField label="PM">
          <select value={pmUserId} onChange={(e) => setPmUserId(e.target.value)}
            className="h-9 w-[130px] 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>
        <SearchField label="설치결과">
          <select value={installResult} onChange={(e) => setInstallResult(e.target.value)}
            className="h-9 w-[110px] rounded border border-gray-300 bg-white px-2 text-sm">
            <option value="">전체</option>
            <option value="OPEN">OPEN</option>
            <option value="CLOSED">CLOSED</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>
  );
}
