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

// asMngList_CS.jsp 대응 - CS등록 및 조치
export default function CsManagePage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [productCd, setProductCd] = useState("");
  const [projectNo, setProjectNo] = useState("");
  const [warranty, setWarranty] = useState("");
  const [recStartDate, setRecStartDate] = useState("");
  const [recEndDate, setRecEndDate] = useState("");
  const [managerId, setManagerId] = useState("");
  const [actStartDate, setActStartDate] = useState("");
  const [actEndDate, setActEndDate] = useState("");
  const [apprStatus, setApprStatus] = useState("");

  const [projectOpts, setProjectOpts] = useState<{ value: string; label: string }[]>([]);
  const [userOpts, setUserOpts] = useState<{ value: string; label: string }[]>([]);
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetch("/api/common/project-list", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })
      .then((r) => r.json())
      .then((j) =>
        setProjectOpts(
          (j.RESULTLIST || []).map((r: Record<string, unknown>) => ({
            value: String(r.OBJID),
            label: String(r.LABEL || r.PROJECT_NO || r.OBJID),
          }))
        )
      )
      .catch(() => setProjectOpts([]));
    fetch("/api/admin/users", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })
      .then((r) => r.json())
      .then((j) =>
        setUserOpts(
          (j.RESULTLIST || []).map((u: Record<string, unknown>) => ({
            value: String(u.USER_ID),
            label: `${u.USER_NAME || u.USER_ID}${u.DEPT_NAME ? ` (${u.DEPT_NAME})` : ""}`,
          }))
        )
      )
      .catch(() => setUserOpts([]));
  }, []);

  const openFormPopup = (objId = "") => {
    const w = 1400, h = 930;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(
      `/cs/manage/form${objId ? `?objId=${objId}` : ""}`,
      "asMngFormPopUp",
      `width=${w},height=${h},left=${left},top=${top}`
    );
  };

  const openFileRegist = (objId: string) => {
    const w = 800, h = 500;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(
      `/common/files?targetObjId=${encodeURIComponent(objId)}&docType=AS_DOC_01&docTypeName=${encodeURIComponent("CS 조치내역 첨부파일")}`,
      "fileAS_DOC_01",
      `width=${w},height=${h},left=${left},top=${top}`
    );
  };

  const openApprovalDetail = (approvalObjId: string) => {
    if (!approvalObjId) return;
    const w = 900, h = 700;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(
      `/approval/form?objId=${approvalObjId}`,
      "approvalDetailPopup",
      `width=${w},height=${h},left=${left},top=${top}`
    );
  };

  const columns: GridColumn[] = [
    {
      title: "접수 No.", field: "SERVICE_NO", width: 110, hozAlign: "left",
      cellClick: (row) => openFormPopup(String(row.OBJID || "")),
    },
    { title: "제품구분(기계형식)", field: "PRODUCT_NAME", width: 140, hozAlign: "left" },
    { title: "프로젝트번호", field: "PROJECT_NO", width: 120, hozAlign: "left" },
    { title: "고객사", field: "CUSTOMER_NAME", width: 130, hozAlign: "left" },
    { title: "출고일자", field: "RELEASE_DATE", width: 100, hozAlign: "center" },
    { title: "셋업지", field: "SETUP", width: 120, hozAlign: "left" },
    { title: "유무상", field: "WARRANTY_NAME", width: 80, hozAlign: "left" },
    { title: "CS구분", field: "CATEGORY_NAME", width: 100, hozAlign: "left" },
    { title: "유형", field: "CATEGORY_H_NAME", width: 100, hozAlign: "left" },
    { title: "제목", field: "TITLE", width: 200, hozAlign: "left" },
    { title: "접수일", field: "REC_DT", width: 100, hozAlign: "center" },
    { title: "예상발생비용", field: "PLAN_COST", width: 110, hozAlign: "right", formatter: "money" },
    { title: "등록자", field: "MANAGER_NAME", width: 90, hozAlign: "left" },
    { title: "조치완료일", field: "ACT_DATE", width: 110, hozAlign: "center" },
    {
      title: "첨부파일", field: "CU03_CNT", width: 80, hozAlign: "center",
      formatter: (cell, row) => (
        <FolderCell
          count={Number(cell) || 0}
          onClick={() => openFileRegist(String(row.OBJID || ""))}
        />
      ),
    },
    {
      title: "상태", field: "APPR_STATUS_NAME", width: 100, hozAlign: "center",
      formatter: (_, row) => {
        const apv = String(row.APPROVAL_OBJID || "");
        return (
          <ApprovalStatusBadge
            status={row.APPR_STATUS_NAME || row.APPR_STATUS}
            onClick={apv ? () => openApprovalDetail(apv) : undefined}
          />
        );
      },
    },
  ];

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/cs/manage", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          Year: year,
          product_cd: productCd,
          project_no: projectNo,
          warranty,
          rec_start_date: recStartDate,
          rec_end_date: recEndDate,
          manager_id: managerId,
          act_start_date: actStartDate,
          act_end_date: actEndDate,
          appr_status: apprStatus,
        }),
      });
      if (res.ok) {
        const json = await res.json();
        setData(json.RESULTLIST || []);
      }
    } finally {
      setLoading(false);
    }
  }, [year, productCd, projectNo, warranty, recStartDate, recEndDate, managerId, actStartDate, actEndDate, apprStatus]);

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

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

  // 단건만 결재 허용 + 이미 진행/완료건 필터
  const approvalRow = selectedRows.length === 1 ? selectedRows[0] : null;
  const approvalStatus = String(approvalRow?.APPR_STATUS_NAME || "");
  const canRequestApproval =
    !!approvalRow && approvalStatus !== "결재중" && approvalStatus !== "결재완료";

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-800">CS관리_CS등록 및 조회</h2>
        <div className="flex gap-2">
          <ApprovalButton
            objIds={approvalRow ? [String(approvalRow.OBJID)] : []}
            targetType="CSM"
            title={approvalRow ? `CS조치내역서 상신 - ${approvalRow.TITLE || approvalRow.SERVICE_NO || ""}` : ""}
            description={approvalRow ? String(approvalRow.TITLE || "") : ""}
            onSuccess={fetchData}
            disabled={!canRequestApproval}
          />
          <Button size="sm" onClick={() => openFormPopup("")}>등록</Button>
          <Button size="sm" variant="danger" onClick={handleDelete}>삭제</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-[110px] 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="제품구분">
          <SearchableCodeSelect codeId="0000001" value={productCd} onChange={setProductCd} className="w-[150px]" />
        </SearchField>
        <SearchField label="프로젝트번호">
          <SearchableSelect options={projectOpts} value={projectNo} onChange={setProjectNo} className="w-[220px]" />
        </SearchField>
        <SearchField label="유/무상">
          <SearchableCodeSelect codeId="0000156" value={warranty} onChange={setWarranty} className="w-[120px]" />
        </SearchField>
        <SearchField label="접수일">
          <div className="flex items-center gap-1">
            <Input type="date" value={recStartDate} onChange={(e) => setRecStartDate(e.target.value)} className="w-[140px]" />
            <span className="text-gray-400">~</span>
            <Input type="date" value={recEndDate} onChange={(e) => setRecEndDate(e.target.value)} className="w-[140px]" />
          </div>
        </SearchField>
        <SearchField label="조치담당자">
          <SearchableSelect options={userOpts} value={managerId} onChange={setManagerId} className="w-[180px]" />
        </SearchField>
        <SearchField label="조치완료일">
          <div className="flex items-center gap-1">
            <Input type="date" value={actStartDate} onChange={(e) => setActStartDate(e.target.value)} className="w-[140px]" />
            <span className="text-gray-400">~</span>
            <Input type="date" value={actEndDate} onChange={(e) => setActEndDate(e.target.value)} className="w-[140px]" />
          </div>
        </SearchField>
        <SearchField label="상태">
          <select
            value={apprStatus}
            onChange={(e) => setApprStatus(e.target.value)}
            className="h-9 w-[130px] rounded border border-gray-300 bg-white px-3 text-sm"
          >
            <option value="">선택</option>
            <option value="inProcess">결재중</option>
            <option value="reject">반려</option>
            <option value="complete">결재완료</option>
          </select>
        </SearchField>
      </SearchForm>

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

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