"use client";

import { useState, useCallback, useEffect, useMemo } from "react";
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/projectMgmtTotalList.jsp)
export default function ProjectTotalPage() {
  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 [rows, setRows] = useState<Record<string, unknown>[]>([]);
  const [selectedObjId, setSelectedObjId] = useState<string>("");

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

  // Gantt 윈도우: 현재년도 기준 3년(이전/당해/다음) × 12개월
  const ganttYear = parseInt(year, 10) || currentYear;
  const ganttStart = new Date(ganttYear - 1, 0, 1);
  const ganttEnd = new Date(ganttYear + 1, 11, 31);
  const ganttMonths = useMemo(() => {
    const list: { y: number; m: number }[] = [];
    for (let y = ganttYear - 1; y <= ganttYear + 1; y++) {
      for (let m = 0; m < 12; m++) list.push({ y, m });
    }
    return list;
  }, [ganttYear]);
  const ganttTotalDays = (ganttEnd.getTime() - ganttStart.getTime()) / 86400000 + 1;

  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}`, "projectModifyPopUp", 500, 400);
  const openWbsPopUp = (objId: string, cat: string) =>
    centerPopup(`/project/wbs-task?OBJID=${objId}&CATEGORY_CD=${cat}`, "wbsTaskPopUp", 1700, 800);
  const openGanttPopUp = (objId: string) =>
    centerPopup(`/project/wbs-gantt?OBJID=${objId}`, "ganttPopUp", 1800, 800);

  const selectedRow = useMemo(
    () => rows.find((r) => String(r.OBJID) === selectedObjId),
    [rows, selectedObjId]
  );

  const fetchData = useCallback(async () => {
    try {
      const res = await fetch("/api/project/total", {
        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();
        const list = (json.RESULTLIST || []) as Record<string, unknown>[];
        setRows(list);
        setSelectedObjId(list.length > 0 ? String(list[0].OBJID) : "");
      }
    } catch {
      Swal.fire("오류", "데이터 조회 중 오류가 발생했습니다.", "error");
    }
  }, [year, projectNo, categoryCd, customerObjid, product, contractStartDate, contractEndDate, location, setup, pmUserId]);

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

  // YYYY-MM-DD 문자열 → 윈도우 내 % (left, width)
  const toPct = (start?: unknown, end?: unknown) => {
    const s = String(start ?? "").slice(0, 10);
    const e = String(end ?? "").slice(0, 10);
    if (!s && !e) return null;
    const sDate = s ? new Date(s) : (e ? new Date(e) : null);
    const eDate = e ? new Date(e) : (s ? new Date(s) : null);
    if (!sDate || !eDate || isNaN(sDate.getTime()) || isNaN(eDate.getTime())) return null;
    if (eDate < ganttStart || sDate > ganttEnd) return null;
    const sClamp = sDate < ganttStart ? ganttStart : sDate;
    const eClamp = eDate > ganttEnd ? ganttEnd : eDate;
    const left = ((sClamp.getTime() - ganttStart.getTime()) / 86400000) / ganttTotalDays * 100;
    const width = Math.max(0.3, ((eClamp.getTime() - sClamp.getTime()) / 86400000 + 1) / ganttTotalDays * 100);
    return { left, width };
  };

  const todayPct = (() => {
    const today = new Date();
    if (today < ganttStart || today > ganttEnd) return null;
    return ((today.getTime() - ganttStart.getTime()) / 86400000) / ganttTotalDays * 100;
  })();

  // 진척율 포맷
  const fmtRate = (v: unknown) => (v == null || v === "" ? 0 : Number(v));

  // 상태 계산: 지연 건수 합 > 0 이면 빨강
  const isLate = (r: Record<string, unknown>) =>
    [r.DESIGN_LATE_CNT, r.PURCHASE_LATE_CNT, r.PRODUCE_LATE_CNT, r.SETUP_LATE_CNT]
      .some((v) => Number(v ?? 0) > 0);

  return (
    <div>
      <h2 className="text-lg font-bold text-gray-800 mb-4">프로젝트종합</h2>

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

      <div className="flex justify-between items-center mb-3">
        <div className="flex items-center gap-3 text-xs">
          <span className="font-semibold text-gray-600">범례:</span>
          <span className="flex items-center gap-1"><span className="inline-block w-3 h-3 rounded-sm" style={{ backgroundColor: "#3b82f6" }} />설계</span>
          <span className="flex items-center gap-1"><span className="inline-block w-3 h-3 rounded-sm" style={{ backgroundColor: "#22c55e" }} />구매</span>
          <span className="flex items-center gap-1"><span className="inline-block w-3 h-3 rounded-sm" style={{ backgroundColor: "#1f2937" }} />조립</span>
          <span className="flex items-center gap-1"><span className="inline-block w-3 h-3 rotate-45" style={{ backgroundColor: "#a855f7" }} />출고</span>
          <span className="flex items-center gap-1"><span className="inline-block w-3 h-3 rounded-sm" style={{ backgroundColor: "#ef4444" }} />셋업</span>
        </div>
        <div className="flex gap-2">
          <Button size="sm" disabled={!selectedRow} onClick={() => selectedRow && openWbsPopUp(String(selectedRow.OBJID), String(selectedRow.CATEGORY_CD ?? ""))}>
            프로젝트 일정
          </Button>
          <Button size="sm" disabled={!selectedRow} onClick={() => selectedRow && openGanttPopUp(String(selectedRow.OBJID))}>
            G-Chart
          </Button>
          <Button size="sm" variant="secondary" onClick={fetchData}>조회</Button>
        </div>
      </div>

      <div className="border border-gray-200 rounded bg-white overflow-hidden">
        <div className="overflow-auto" style={{ maxHeight: "calc(100vh - 430px)" }}>
          <table className="text-xs border-collapse" style={{ minWidth: "1600px", width: "100%" }}>
            <thead className="sticky top-0 z-10 bg-gray-50">
              <tr>
                <th rowSpan={2} className="w-10 border border-gray-200 px-1 py-1 bg-gray-100">선택</th>
                <th colSpan={5} className="border border-gray-200 px-2 py-1 bg-gray-100 text-center">프로젝트 정보</th>
                <th colSpan={6} className="border border-gray-200 px-2 py-1 bg-gray-100 text-center">진척율(%)</th>
                <th colSpan={12} className="border border-gray-200 px-2 py-1 text-center" style={{ backgroundColor: "#fef3c7" }}>{ganttYear - 1}년</th>
                <th colSpan={12} className="border border-gray-200 px-2 py-1 text-center" style={{ backgroundColor: "#dbeafe" }}>{ganttYear}년</th>
                <th colSpan={12} className="border border-gray-200 px-2 py-1 text-center" style={{ backgroundColor: "#dcfce7" }}>{ganttYear + 1}년</th>
              </tr>
              <tr>
                <th className="border border-gray-200 px-1 py-1 bg-gray-50" style={{ width: 100 }}>고객사</th>
                <th className="border border-gray-200 px-1 py-1 bg-gray-50" style={{ width: 70 }}>제품구분</th>
                <th className="border border-gray-200 px-1 py-1 bg-gray-50" style={{ width: 90 }}>프로젝트번호</th>
                <th className="border border-gray-200 px-1 py-1 bg-gray-50" style={{ width: 160 }}>프로젝트명</th>
                <th className="border border-gray-200 px-1 py-1 bg-gray-50" style={{ width: 70 }}>제작공장</th>
                <th className="border border-gray-200 px-1 py-1 bg-gray-50" style={{ width: 80 }}>요청납기일</th>
                <th className="border border-gray-200 px-1 py-1 bg-gray-50" style={{ width: 50 }}>설계</th>
                <th className="border border-gray-200 px-1 py-1 bg-gray-50" style={{ width: 50 }}>구매</th>
                <th className="border border-gray-200 px-1 py-1 bg-gray-50" style={{ width: 50 }}>조립</th>
                <th className="border border-gray-200 px-1 py-1 bg-gray-50" style={{ width: 50 }}>셋업</th>
                <th className="border border-gray-200 px-1 py-1 bg-gray-50" style={{ width: 50 }}>상태</th>
                {ganttMonths.map((mm, i) => (
                  <th key={i} className="border border-gray-200 px-1 py-1 bg-gray-50 text-[10px]" style={{ width: 30 }}>
                    {mm.m + 1}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {rows.length === 0 ? (
                <tr>
                  <td colSpan={48} className="text-center py-12 text-gray-400">조회된 데이터가 없습니다.</td>
                </tr>
              ) : (
                rows.map((row) => {
                  const objId = String(row.OBJID);
                  const isSelected = objId === selectedObjId;
                  const design = toPct(row.DESIGN_ACT_START, row.DESIGN_ACT_END);
                  const purchase = toPct(row.PURCHASE_ACT_START, row.PURCHASE_ACT_END);
                  const produce = toPct(row.PRODUCE_ACT_START, row.PRODUCE_ACT_END);
                  const ship = toPct(row.REQ_DEL_DATE, row.REQ_DEL_DATE);
                  const setupBar = toPct(row.SETUP_ACT_START, row.SETUP_ACT_END);
                  const late = isLate(row);

                  return (
                    <tr
                      key={objId}
                      className={`cursor-pointer ${isSelected ? "bg-blue-50" : "hover:bg-gray-50"}`}
                      onClick={() => setSelectedObjId(objId)}
                    >
                      <td className="border border-gray-200 text-center">
                        <input
                          type="radio"
                          name="selectProject"
                          checked={isSelected}
                          onChange={() => setSelectedObjId(objId)}
                        />
                      </td>
                      <td className="border border-gray-200 px-2 py-1 truncate" title={String(row.CUSTOMER_NAME ?? "")}>{String(row.CUSTOMER_NAME ?? "")}</td>
                      <td className="border border-gray-200 px-2 py-1 truncate">{String(row.PRODUCT_NAME ?? "")}</td>
                      <td className="border border-gray-200 px-2 py-1 text-primary hover:underline" onClick={(e) => { e.stopPropagation(); openProjectModify(objId); }}>
                        {String(row.PROJECT_NO ?? "")}
                      </td>
                      <td className="border border-gray-200 px-2 py-1 truncate">{String(row.PROJECT_NAME ?? "")}</td>
                      <td className="border border-gray-200 px-2 py-1 text-center">{String(row.MANUFACTURE_PLANT_NAME ?? "")}</td>
                      <td className="border border-gray-200 px-2 py-1 text-center">{String(row.REQ_DEL_DATE ?? "")}</td>
                      <td className="border border-gray-200 px-1 py-1 text-center">{fmtRate(row.DESIGN_RATETOTAL)}</td>
                      <td className="border border-gray-200 px-1 py-1 text-center">{fmtRate(row.PURCHASE_RATETOTAL)}</td>
                      <td className="border border-gray-200 px-1 py-1 text-center">{fmtRate(row.PRODUCE_RATETOTAL)}</td>
                      <td className="border border-gray-200 px-1 py-1 text-center">{fmtRate(row.SETUP_RATETOTAL)}</td>
                      <td className="border border-gray-200 px-1 py-1 text-center">
                        <span className={`inline-block w-3 h-3 rounded-full ${late ? "bg-red-500" : "bg-green-500"}`} />
                      </td>
                      <td colSpan={36} className="border border-gray-200 relative p-0" style={{ height: 48 }}>
                        {todayPct != null && (
                          <div className="absolute top-0 bottom-0 border-l-2 border-dotted" style={{ left: `${todayPct}%`, borderColor: "#f59e0b" }} title="오늘" />
                        )}
                        {design && (
                          <div className="absolute rounded-sm" title={`설계: ${row.DESIGN_ACT_START} ~ ${row.DESIGN_ACT_END}`}
                               style={{ top: 4, left: `${design.left}%`, width: `${design.width}%`, height: 4, backgroundColor: "#3b82f6" }} />
                        )}
                        {purchase && (
                          <div className="absolute rounded-sm" title={`구매: ${row.PURCHASE_ACT_START} ~ ${row.PURCHASE_ACT_END}`}
                               style={{ top: 12, left: `${purchase.left}%`, width: `${purchase.width}%`, height: 4, backgroundColor: "#22c55e" }} />
                        )}
                        {produce && (
                          <div className="absolute rounded-sm" title={`조립: ${row.PRODUCE_ACT_START} ~ ${row.PRODUCE_ACT_END}`}
                               style={{ top: 20, left: `${produce.left}%`, width: `${produce.width}%`, height: 4, backgroundColor: "#1f2937" }} />
                        )}
                        {ship && (
                          <div className="absolute rotate-45" title={`출고: ${row.REQ_DEL_DATE}`}
                               style={{ top: 28, left: `calc(${ship.left}% - 4px)`, width: 8, height: 8, backgroundColor: "#a855f7" }} />
                        )}
                        {setupBar && (
                          <div className="absolute rounded-sm" title={`셋업: ${row.SETUP_ACT_START} ~ ${row.SETUP_ACT_END}`}
                               style={{ top: 38, left: `${setupBar.left}%`, width: `${setupBar.width}%`, height: 4, backgroundColor: "#ef4444" }} />
                        )}
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
