"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 { ExcelDownloadButton } from "@/components/ui/excel-download-button";
import Swal from "sweetalert2";

// 제품관리_설계변경 리스트 (원본: partMng/partMngHisList.jsp)
export default function DesignChangePage() {
  const currentYear = new Date().getFullYear();
  const [year, setYear] = useState("");
  const [contractObjid, setContractObjid] = useState("");
  const [unitCode, setUnitCode] = useState("");
  const [partNo, setPartNo] = useState("");
  const [partName, setPartName] = useState("");
  const [changeOption, setChangeOption] = useState("");
  const [eoStart, setEoStart] = useState("");
  const [eoEnd, setEoEnd] = useState("");
  const [changeType, setChangeType] = useState("");
  const [partType, setPartType] = useState("");
  const [writerId, setWriterId] = useState("");

  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [loading, setLoading] = useState(false);
  const [projects, setProjects] = useState<{ value: string; label: string }[]>([]);
  const [units, setUnits] = useState<{ value: string; label: string }[]>([]);
  const [users, setUsers] = useState<{ value: string; label: string }[]>([]);

  // 프로젝트 목록 로드
  useEffect(() => {
    fetch("/api/common/project-list", {
      method: "POST", headers: { "Content-Type": "application/json" }, body: "{}",
    }).then((r) => r.json())
      .then((j) => setProjects((j.RESULTLIST || []).map((r: Record<string, unknown>) => ({
        value: String(r.OBJID), label: String(r.LABEL || r.PROJECT_NO || r.OBJID),
      }))))
      .catch(() => {});
  }, []);

  // 프로젝트 변경 시 유닛 목록 로드
  useEffect(() => {
    if (!contractObjid) { setUnits([]); return; }
    fetch("/api/common/unit-list", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ contract_objid: contractObjid }),
    }).then((r) => r.json())
      .then((j) => setUnits((j.RESULTLIST || []).map((r: Record<string, unknown>) => ({
        value: String(r.OBJID), label: String(r.UNIT_NAME || r.TASK_NAME),
      }))))
      .catch(() => {});
    setUnitCode("");
  }, [contractObjid]);

  // 사용자 목록 로드
  useEffect(() => {
    fetch("/api/admin/users", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })
      .then((r) => r.json())
      .then((j) => setUsers((j.RESULTLIST || []).map((r: Record<string, unknown>) => ({
        value: String(r.USER_ID), label: String(r.USER_NAME || ""),
      }))))
      .catch(() => {});
  }, []);

  const openHisDetail = (objId: string) => {
    const w = 800, h = 550;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(
      `/product/popup/part-his-detail?objId=${encodeURIComponent(objId)}`,
      "partMngHisDetailPopUp",
      `width=${w},height=${h},left=${left},top=${top}`,
    );
  };

  const columns: GridColumn[] = [
    { title: "EO No", field: "EO_NO", width: 85, hozAlign: "left" },
    { title: "프로젝트번호", field: "PROJECT_NO", width: 100, hozAlign: "left" },
    { title: "프로젝트명", field: "PROJECT_NAME", width: 150, hozAlign: "left" },
    { title: "유닛명", field: "UNIT_NAME", width: 150, hozAlign: "left" },
    { title: "모품번", field: "PARENT_PART_INFO", width: 150, hozAlign: "left" },
    {
      title: "품번", field: "PART_NO", width: 150, hozAlign: "left",
      cellClick: (row) => openHisDetail(String(row.OBJID)),
    },
    { title: "품명", field: "PART_NAME", hozAlign: "left" },
    { title: "수량", field: "QTY", width: 55, hozAlign: "center" },
    { title: "변경수량", field: "QTY_TEMP", width: 75, hozAlign: "center" },
    { title: "EO구분", field: "CHANGE_TYPE_NAME", width: 75, hozAlign: "center" },
    { title: "EO사유", field: "CHANGE_OPTION_NAME", width: 75, hozAlign: "center" },
    { title: "Revision", field: "REVISION", width: 85, hozAlign: "center" },
    { title: "EO Date", field: "EO_DATE", width: 85, hozAlign: "center" },
    { title: "PART구분", field: "PART_TYPE_NAME", width: 90, hozAlign: "center" },
    { title: "담당자", field: "WRITER_NAME", width: 80, hozAlign: "center" },
    { title: "실행일", field: "HIS_REG_DATE_TITLE", width: 80, hozAlign: "center" },
  ];

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/product/design-change", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          Year: year,
          contract_objid: contractObjid,
          unit_code: unitCode,
          part_no: partNo,
          part_name: partName,
          change_option: changeOption,
          eo_start_date: eoStart,
          eo_end_date: eoEnd,
          change_type: changeType,
          part_type: partType,
          writer_id: writerId,
        }),
      });
      if (res.ok) {
        const json = await res.json();
        setData(json.RESULTLIST || []);
      }
    } catch {
      Swal.fire("오류", "데이터 조회 중 오류가 발생했습니다.", "error");
    } finally {
      setLoading(false);
    }
  }, [year, contractObjid, unitCode, partNo, partName, changeOption, eoStart, eoEnd, changeType, partType, writerId]);

  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" onClick={fetchData}>조회</Button>
          <ExcelDownloadButton data={data} columns={columns} filename="제품관리_설계변경리스트" />
          <Button size="sm" variant="secondary" onClick={() => {
            setYear(""); setContractObjid(""); setUnitCode("");
            setPartNo(""); setPartName(""); setChangeOption("");
            setEoStart(""); setEoEnd(""); setChangeType(""); setPartType(""); setWriterId("");
          }}>초기화</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={projects} value={contractObjid} onChange={setContractObjid} className="w-[200px]" />
        </SearchField>
        <SearchField label="유닛명">
          <SearchableSelect options={units} value={unitCode} onChange={setUnitCode} className="w-[220px]" />
        </SearchField>
        <SearchField label="품번">
          <Input value={partNo} onChange={(e) => setPartNo(e.target.value)} className="w-[140px]" />
        </SearchField>
        <SearchField label="품명">
          <Input value={partName} onChange={(e) => setPartName(e.target.value)} className="w-[140px]" />
        </SearchField>
        <SearchField label="EO사유">
          <SearchableCodeSelect codeId="0000318" value={changeOption} onChange={setChangeOption} className="w-[120px]" />
        </SearchField>
        <SearchField label="EO Date">
          <div className="flex items-center gap-1">
            <Input type="date" value={eoStart} onChange={(e) => setEoStart(e.target.value)} className="w-[140px]" />
            <span>~</span>
            <Input type="date" value={eoEnd} onChange={(e) => setEoEnd(e.target.value)} className="w-[140px]" />
          </div>
        </SearchField>
        <SearchField label="EO구분">
          <SearchableCodeSelect codeId="0001054" value={changeType} onChange={setChangeType} className="w-[120px]" />
        </SearchField>
        <SearchField label="PART 구분">
          <SearchableCodeSelect codeId="0000062" value={partType} onChange={setPartType} className="w-[120px]" />
        </SearchField>
        <SearchField label="담당자">
          <SearchableSelect options={users} value={writerId} onChange={setWriterId} className="w-[140px]" />
        </SearchField>
      </SearchForm>

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