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

// 프로젝트관리_진행관리 (원본: project/projectMgmtList.jsp)
export default function ProjectStatusPage() {
  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`);
  };

  // 원본: openProjectFormPopUp → /project/projectmodifyPopUp.do?OBJID=xxx (420x350)
  const openProjectModify = (objId: string) => centerPopup(`/project/modify?objId=${objId}`, "projectModifyPopUp", 500, 400);
  // 원본: openIssueFormPopUp(status,projectobjid) → /productionplanning/issuemgmtList.do (1720x900)
  const openIssuePopUp = (status: string, objId: string) =>
    centerPopup(`/production/issue-popup?status=${status}&project_no=${objId}`, "issueListPopUp", 1720, 900);
  // 원본: fn_openInvestmentCostPricePopUp
  const openInvestCost = (projectObjId: string, productObjId: string, milestoneObjId: string) =>
    centerPopup(
      `/project/invest-cost?projectObjId=${projectObjId}&productObjId=${productObjId}&milestoneObjId=${milestoneObjId}`,
      "investCostPopUp", 1200, 800,
    );
  // 원본: wbs_popup
  const openWbsPopUp = (objId: string, categoryCd: string) =>
    centerPopup(`/project/wbs-task?OBJID=${objId}&CATEGORY_CD=${categoryCd}&actionType=view`, "wbsTaskPopUp", 1700, 800);
  // 원본: setup_wbs_popup
  const openSetupWbsPopUp = (objId: string) =>
    centerPopup(`/project/wbs-setup?OBJID=${objId}`, "setupWbsPopUp", 1100, 750);

  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: 140, hozAlign: "left" },
        { title: "프로젝트명", field: "PROJECT_NAME", width: 180, hozAlign: "left" },
        { title: "고객납기일", field: "REQ_DEL_DATE", width: 100, hozAlign: "center" },
        { title: "셋업지", field: "SETUP", width: 100, hozAlign: "center" },
        { title: "설비방향", field: "FACILITY_NAME", width: 100, hozAlign: "center" },
        { title: "PM", field: "PM_USER_NAME", width: 90, hozAlign: "center" },
        { title: "제작공장", field: "MANUFACTURE_PLANT_NAME", width: 100, hozAlign: "center" },
        { title: "예상납기일", field: "CONTRACT_DEL_DATE", width: 100, hozAlign: "center" },
      ],
    },
    {
      title: "현황", headerHozAlign: "center",
      columns: [
        {
          title: "이슈(건수)", headerHozAlign: "center",
          columns: [
            {
              title: "발생", field: "ISSUE_CNT", width: 60, hozAlign: "center",
              cellClick: (row) => openIssuePopUp("all", String(row.OBJID)),
            },
            {
              title: "조치", field: "COMP_CNT", width: 60, hozAlign: "center",
              cellClick: (row) => openIssuePopUp("complete", String(row.OBJID)),
            },
            {
              title: "미결", field: "MISS_CNT", width: 60, hozAlign: "center",
              cellClick: (row) => openIssuePopUp("late", String(row.OBJID)),
            },
            {
              title: "조치율", field: "ISSUE_RATE", width: 70, hozAlign: "center",
              formatter: (_c, row) => `${row.ISSUE_RATE ?? 0}%`,
            },
          ],
        },
        {
          title: "투입원가", headerHozAlign: "center",
          columns: [
            {
              title: "목표가", field: "TOTAL_COST_GOAL", width: 110, hozAlign: "right", formatter: "money",
              cellClick: (row) => openInvestCost(
                String(row.OBJID), String(row.PROD_REL_OBJID ?? ""), String(row.MILESTONE_OBJID ?? ""),
              ),
            },
            {
              title: "투입금액", field: "TOTAL_COST_ACTUAL", width: 110, hozAlign: "right", formatter: "money",
              cellClick: (row) => openInvestCost(
                String(row.OBJID), String(row.PROD_REL_OBJID ?? ""), String(row.MILESTONE_OBJID ?? ""),
              ),
            },
            {
              title: "투입율(%)", field: "TOTAL_INPUT_RATE", width: 80, hozAlign: "center",
              formatter: (_c, row) => `${row.TOTAL_INPUT_RATE ?? 0}%`,
              cellClick: (row) => openInvestCost(
                String(row.OBJID), String(row.PROD_REL_OBJID ?? ""), String(row.MILESTONE_OBJID ?? ""),
              ),
            },
          ],
        },
        {
          title: "진척율(%)", headerHozAlign: "center",
          columns: [
            {
              title: "전체공정", field: "TOTAL_RATE", width: 80, hozAlign: "center",
              formatter: (_c, row) => `${row.TOTAL_RATE ?? 0}%`,
              cellClick: (row) => openWbsPopUp(String(row.OBJID), String(row.CATEGORY_CD ?? "")),
            },
            {
              title: "셋업", field: "SETUP_RATE", width: 70, hozAlign: "center",
              formatter: (_c, row) => `${row.SETUP_RATE ?? 0}%`,
              cellClick: (row) => openSetupWbsPopUp(String(row.OBJID)),
            },
          ],
        },
        {
          title: "출고", headerHozAlign: "center",
          columns: [
            { title: "출고여부", field: "RELEASE_STATUS_TITLE", width: 80, hozAlign: "center" },
            { title: "출고일", field: "RELEASE_DATE", width: 100, hozAlign: "center" },
          ],
        },
      ],
    },
  ];

  const fetchData = useCallback(async () => {
    try {
      const res = await fetch("/api/project/status", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          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">프로젝트관리_진행관리</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>
  );
}
