"use client";

import { useState, useCallback, useEffect } from "react";
import Swal from "sweetalert2";
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";

// productionplanning/issuemgmtList.jsp 대응 - 생산관리_이슈관리
function openPopup(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},scrollbars=yes,resizable=yes`);
}

export default function ProductionIssuePage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [projectNo, setProjectNo] = useState("");
  const [unitCode, setUnitCode] = useState("");
  const [issueCategory, setIssueCategory] = useState("");
  const [issueType, setIssueType] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selected, setSelected] = useState<Record<string, unknown>[]>([]);

  const openProjectForm = (objId: string) =>
    openPopup(`/project/modify?objId=${encodeURIComponent(objId)}`, "projectForm", 520, 650);
  const openIssueForm = (objId: string) =>
    openPopup(`/production/issue/form?objId=${encodeURIComponent(objId)}`, "issueForm", 1100, 800);

  const handleRegister = () => openIssueForm("");

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/production/issue", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year, project_no: projectNo, unit_code: unitCode,
        issue_category: issueCategory, issue_type: issueType,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [year, projectNo, unitCode, issueCategory, issueType]);

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

  useEffect(() => {
    (window as unknown as { fn_search?: () => void }).fn_search = fetchData;
    return () => { delete (window as unknown as { fn_search?: () => void }).fn_search; };
  }, [fetchData]);

  const handleAction = async (action: "delete" | "release") => {
    if (selected.length === 0) {
      Swal.fire({ icon: "warning", title: "선택된 대상이 없습니다." });
      return;
    }
    const targets = selected.filter((r) => String(r.STATUS || "") === "write");
    if (targets.length === 0) {
      Swal.fire({ icon: "warning", title: "등록중인 데이터만 처리 가능합니다." });
      return;
    }
    const title = action === "delete" ? "선택된 데이터를 삭제하시겠습니까?" : "선택된 데이터를 배포하시겠습니까?";
    const r = await Swal.fire({
      title, icon: "warning",
      showCancelButton: true, confirmButtonText: "확인", cancelButtonText: "취소",
    });
    if (!r.isConfirmed) return;

    const objIds = targets.map((t) => String(t.OBJID));
    const res = await fetch("/api/production/issue/save", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ actionType: action, objIds }),
    });
    const j = await res.json();
    if (j.success) {
      await Swal.fire({ icon: "success", title: j.message || "완료", timer: 1000, showConfirmButton: false });
      fetchData();
    } else {
      Swal.fire("오류", j.message || "처리 실패", "error");
    }
  };

  const columns: GridColumn[] = [
    { title: "이슈번호", field: "ISSUE_NO", width: 110, hozAlign: "center",
      cellClick: (row) => openIssueForm(String(row.OBJID)) },
    { title: "프로젝트번호", field: "PROJECT_NO", width: 110, hozAlign: "center",
      cellClick: (row) => openProjectForm(String(row.PROJECT_OBJID)) },
    { title: "유닛명", field: "UNIT_CODE_NAME", width: 140, hozAlign: "left" },
    { title: "품번", field: "PART_NO", width: 120, hozAlign: "left" },
    { title: "품명", field: "PART_NAME", width: 140, hozAlign: "left" },
    { title: "이슈구분", field: "ISSUE_CATEGORY_NAME", width: 100, hozAlign: "center" },
    { title: "이슈유형", field: "ISSUE_TYPE_NAME", width: 100, hozAlign: "center" },
    { title: "이슈내용", field: "CONTENT", width: 220, hozAlign: "left" },
    { title: "등록일", field: "REG_DATE_TEXT", width: 100, hozAlign: "center" },
    { title: "등록자", field: "WRITER_NAME", width: 80, hozAlign: "center" },
    { title: "설계담당자", field: "DESIGN_USERID_NAME", width: 100, hozAlign: "center" },
    { title: "구매담당자", field: "PURCHASE_USERID_NAME", width: 100, hozAlign: "center" },
    { title: "품질담당자", field: "QUALITY_USERID_NAME", width: 100, hozAlign: "center" },
    { title: "생산담당자", field: "PRODUCTION_USERID_NAME", width: 100, hozAlign: "center" },
    { title: "조치결과", field: "DESIGN_RESULT_NAME", width: 100, hozAlign: "center" },
    { title: "조치일", field: "DESIGN_DATE", width: 100, hozAlign: "center" },
    { title: "상태", field: "STATUS_NAME", width: 80, hozAlign: "center" },
  ];

  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={() => handleAction("delete")}>삭제</Button>
          <Button size="sm" onClick={() => handleAction("release")}>배포</Button>
          <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-3 text-sm">
            <option value="">선택</option>
            {Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - i).map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
        </SearchField>
        <SearchField label="프로젝트번호">
          <Input value={projectNo} onChange={(e) => setProjectNo(e.target.value)} className="w-[160px]" />
        </SearchField>
        <SearchField label="유닛명">
          <Input value={unitCode} onChange={(e) => setUnitCode(e.target.value)} className="w-[140px]" />
        </SearchField>
        <SearchField label="이슈구분">
          <CodeSelect codeId="ISSUE_CATEGORY" value={issueCategory} onChange={setIssueCategory} className="w-[140px]" />
        </SearchField>
        <SearchField label="이슈유형">
          <CodeSelect codeId={issueCategory || "ISSUE_TYPE"} value={issueType} onChange={setIssueType} className="w-[140px]" />
        </SearchField>
      </SearchForm>

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

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