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

// 프로젝트관리_일정관리(WBS) (원본: project/projectMgmtWbsList.jsp)
export default function ProjectProgressPage() {
  const currentYear = new Date().getFullYear();
  const [year, setYear] = useState(String(currentYear));
  const [projectNo, setProjectNo] = useState("");
  const [categoryCd, setCategoryCd] = useState("");
  const [customerObjid, setCustomerObjid] = useState("");
  const [product, setProduct] = useState("");
  const [contractStartDate, setContractStartDate] = useState("");
  const [contractEndDate, setContractEndDate] = useState("");
  const [location, setLocation] = useState("");
  const [setup, setSetup] = useState("");
  const [pmUserId, setPmUserId] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  const [projectNoOpts, setProjectNoOpts] = useState<{ value: string; label: string }[]>([]);
  const [customers, setCustomers] = useState<{ value: string; label: string }[]>([]);
  const [pmUsers, setPmUsers] = useState<{ value: string; label: string }[]>([]);

  useEffect(() => {
    fetch("/api/sales/contract/projects", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })
      .then((r) => r.json())
      .then((d) => setProjectNoOpts((d.rows || []).map((r: Record<string, unknown>) => ({
        value: String(r.CODE ?? r.code ?? ""),
        label: String(r.NAME ?? r.name ?? ""),
      }))))
      .catch(() => {});
    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 centerPopup = (url: string, name: string, w: number, h: number) => {
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(url, name, `width=${w},height=${h},left=${left},top=${top},menubars=no,scrollbars=yes,resizable=yes`);
  };

  const openProjectModify = (objId: string) =>
    centerPopup(`/project/modify?objId=${objId}&actionType=edit`, "projectModifyPopUp", 500, 400);
  const openWbsPopUp = (objId: string, categoryCd: string) =>
    centerPopup(`/project/wbs-task?OBJID=${objId}&CATEGORY_CD=${categoryCd}`, "wbsTaskPopUp", 1700, 800);
  const openSetupWbsPopUp = (objId: string) =>
    centerPopup(`/project/wbs-setup?OBJID=${objId}`, "setupWbsPopUp", 1100, 750);

  // 카테고리별 클릭 팝업 — 설계/구매/제작은 wbs, 셋업은 setup_wbs
  const wbsClick = (row: Record<string, unknown>) =>
    openWbsPopUp(String(row.OBJID), String(row.CATEGORY_CD ?? ""));
  const setupClick = (row: Record<string, unknown>) => openSetupWbsPopUp(String(row.OBJID));

  const columns: GridColumn[] = [
    {
      title: "프로젝트번호", field: "PROJECT_NO", width: 100, frozen: true, hozAlign: "left",
      cellClick: (row) => openProjectModify(String(row.OBJID)),
    },
    {
      title: "프로젝트정보", headerHozAlign: "center",
      columns: [
        { title: "계약구분", field: "CATEGORY_NAME", width: 80, hozAlign: "center" },
        { title: "차수", field: "OVERHAUL_ORDER", width: 60, hozAlign: "center" },
        { title: "고객사", field: "CUSTOMER_NAME", width: 120, hozAlign: "left" },
        { title: "당사프로젝트명", field: "PROJECT_NAME", width: 160, hozAlign: "left" },
        { title: "요청납기일", field: "REQ_DEL_DATE", width: 100, hozAlign: "center" },
        { title: "셋업지", field: "SETUP", width: 90, hozAlign: "center" },
        { title: "PM", field: "PM_USER_NAME", width: 80, hozAlign: "center" },
        { title: "제작공장", field: "MANUFACTURE_PLANT_NAME", width: 100, hozAlign: "center" },
      ],
    },
    {
      title: "설계 및 구매", headerHozAlign: "center",
      columns: [
        {
          title: "설계관리", headerHozAlign: "center",
          columns: [
            {
              title: "공정율(%)", field: "DESIGN_RATETOTAL", width: 90, hozAlign: "center",
              formatter: (_c, row) => `${row.DESIGN_RATETOTAL ?? 0}%`,
              cellClick: wbsClick,
            },
            { title: "🟢 완료", field: "DESIGN_COMP_CNT", width: 80, hozAlign: "center", cellClick: wbsClick },
            { title: "🟡 지연완료", field: "DESIGN_LATE_COMP_CNT", width: 90, hozAlign: "center", cellClick: wbsClick },
            { title: "🔵 진행중", field: "DESIGN_ING_CNT", width: 80, hozAlign: "center", cellClick: wbsClick },
            { title: "🔴 지연", field: "DESIGN_LATE_CNT", width: 80, hozAlign: "center", cellClick: wbsClick },
          ],
        },
        {
          title: "구매관리", headerHozAlign: "center",
          columns: [
            {
              title: "공정율(%)", field: "PURCHASE_RATETOTAL", width: 90, hozAlign: "center",
              formatter: (_c, row) => `${row.PURCHASE_RATETOTAL ?? 0}%`,
              cellClick: wbsClick,
            },
            { title: "🟢 완료", field: "PURCHASE_COMP_CNT", width: 80, hozAlign: "center", cellClick: wbsClick },
            { title: "🟡 지연완료", field: "PURCHASE_LATE_COMP_CNT", width: 90, hozAlign: "center", cellClick: wbsClick },
            { title: "🔵 진행중", field: "PURCHASE_ING_CNT", width: 80, hozAlign: "center", cellClick: wbsClick },
            { title: "🔴 지연", field: "PURCHASE_LATE_CNT", width: 80, hozAlign: "center", cellClick: wbsClick },
          ],
        },
      ],
    },
    {
      title: "설비조립 및 셋업", headerHozAlign: "center",
      columns: [
        {
          title: "조립(제작)관리", headerHozAlign: "center",
          columns: [
            {
              title: "공정율(%)", field: "PRODUCE_RATETOTAL", width: 90, hozAlign: "center",
              formatter: (_c, row) => `${row.PRODUCE_RATETOTAL ?? 0}%`,
              cellClick: wbsClick,
            },
            { title: "🟢 완료", field: "PRODUCE_COMP_CNT", width: 80, hozAlign: "center", cellClick: wbsClick },
            { title: "🟡 지연완료", field: "PRODUCE_LATE_COMP_CNT", width: 90, hozAlign: "center", cellClick: wbsClick },
            { title: "🔵 진행중", field: "PRODUCE_ING_CNT", width: 80, hozAlign: "center", cellClick: wbsClick },
            { title: "🔴 지연", field: "PRODUCE_LATE_CNT", width: 80, hozAlign: "center", cellClick: wbsClick },
          ],
        },
        {
          title: "셋업관리", headerHozAlign: "center",
          columns: [
            {
              title: "공정율(%)", field: "SETUP_RATETOTAL", width: 90, hozAlign: "center",
              formatter: (_c, row) => `${row.SETUP_RATETOTAL ?? 0}%`,
              cellClick: setupClick,
            },
            { title: "완료", field: "SETUP_COMP_CNT", width: 80, hozAlign: "center", cellClick: setupClick },
            { title: "지연완료", field: "SETUP_LATE_COMP_CNT", width: 90, hozAlign: "center", cellClick: setupClick },
            { title: "진행중", field: "SETUP_ING_CNT", width: 80, hozAlign: "center", cellClick: setupClick },
            { title: "지연", field: "SETUP_LATE_CNT", width: 80, hozAlign: "center", cellClick: setupClick },
          ],
        },
      ],
    },
  ];

  const fetchData = useCallback(async () => {
    try {
      const res = await fetch("/api/project/progress", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          Year: year,
          project_no: projectNo,
          category_cd: categoryCd,
          customer_objid: customerObjid,
          product,
          contract_start_date: contractStartDate,
          contract_end_date: contractEndDate,
          location,
          setup,
          pm_user_id: pmUserId,
        }),
      });
      if (res.ok) {
        const json = await res.json();
        setData(json.RESULTLIST || []);
      }
    } catch {
      Swal.fire("오류", "데이터 조회 중 오류가 발생했습니다.", "error");
    }
  }, [year, projectNo, categoryCd, customerObjid, product, contractStartDate, contractEndDate, location, setup, pmUserId]);

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

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-800">프로젝트관리_일정관리(WBS)</h2>
        <div className="flex gap-2">
          <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="프로젝트번호">
          <SearchableSelect options={projectNoOpts} value={projectNo} onChange={setProjectNo} className="w-[240px]" />
        </SearchField>
        <SearchField label="계약구분">
          <SearchableCodeSelect codeId="0000167" value={categoryCd} onChange={setCategoryCd} className="w-[130px]" />
        </SearchField>
        <SearchField label="고객사">
          <SearchableSelect options={customers} value={customerObjid} onChange={setCustomerObjid} className="w-[180px]" />
        </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="입고지">
          <Input value={location} onChange={(e) => setLocation(e.target.value)} className="w-[130px]" />
        </SearchField>
        <SearchField label="셋업지">
          <Input value={setup} onChange={(e) => setSetup(e.target.value)} className="w-[130px]" />
        </SearchField>
        <SearchField label="PM">
          <SearchableSelect options={pmUsers} value={pmUserId} onChange={setPmUserId} className="w-[160px]" />
        </SearchField>
      </SearchForm>

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