"use client";

import { Suspense, useCallback, useEffect, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import Swal from "sweetalert2";
import { DataGrid, type GridColumn } from "@/components/grid/data-grid";
import { SearchForm, SearchField } from "@/components/layout/search-form";
import { Button } from "@/components/ui/button";
import { SearchableSelect } from "@/components/ui/searchable-select";
import { numberWithCommas } from "@/lib/utils";

// productionplanning/workStatusByProjectList.jsp + workStatusByImployeeList.jsp 대응
// 탭: 프로젝트 작업현황 / 담당자별 작업현황
type Tab = "project" | "employee";

interface Option { value: string; label: string }

interface ProjectSumMap {
  SUM_DESIGN_INPUT?: number;
  SUM_PURCHASE_INPUT?: number;
  SUM_SALES_INPUT?: number;
  SUM_PRODUCTION_MGMT_INPUT?: number;
  SUM_PRODUCTION_INPUT?: number;
  SUM_MGMT_INPUT?: number;
  SUM_OUTSOURCING?: number;
  SUM_WORK_HOUR?: number;
  SUM_MAN_DAY?: number;
  SUM_MAN_MONTH?: number;
}

interface EmployeeSumMap {
  SUM_WORK_HOUR?: number;
  SUM_MAN_DAY?: number;
  SUM_MAN_MONTH?: number;
}

export default function WorkStatusPage() {
  return (
    <Suspense fallback={<div className="p-8 text-center text-gray-400">로딩 중...</div>}>
      <WorkStatusContent />
    </Suspense>
  );
}

function WorkStatusContent() {
  const searchParams = useSearchParams();
  const tabParam = searchParams.get("tab");
  const [tab, setTab] = useState<Tab>(tabParam === "employee" ? "employee" : "project");

  // 메뉴 재클릭 등으로 ?tab= 변경될 때 탭 동기화
  useEffect(() => {
    if (tabParam === "employee" || tabParam === "project") setTab(tabParam);
  }, [tabParam]);

  // 공용 드롭다운 옵션
  const [projectOptions, setProjectOptions] = useState<Option[]>([]);
  const [deptOptions, setDeptOptions] = useState<Option[]>([]);
  const [workerOptions, setWorkerOptions] = useState<Option[]>([]);

  useEffect(() => {
    fetch("/api/common/project-list", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })
      .then((r) => r.json())
      .then((d) => {
        const rows = (d.RESULTLIST || []) as Record<string, unknown>[];
        setProjectOptions(rows.map((r) => ({
          value: String(r.OBJID ?? ""),
          label: String(r.LABEL ?? r.PROJECT_NO ?? ""),
        })));
      })
      .catch(() => setProjectOptions([]));

    fetch("/api/common/dept-list", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })
      .then((r) => r.json())
      .then((d) => {
        const rows = (d.RESULTLIST || []) as Record<string, unknown>[];
        setDeptOptions(rows.map((r) => ({
          value: String(r.DEPT_CODE ?? ""),
          label: String(r.DEPT_NAME ?? ""),
        })));
      })
      .catch(() => setDeptOptions([]));

    fetch("/api/common/user-list", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })
      .then((r) => r.json())
      .then((d) => {
        const rows = (d.RESULTLIST || []) as Record<string, unknown>[];
        setWorkerOptions(rows.map((r) => ({
          value: String(r.USER_ID ?? ""),
          label: `${r.DEPT_NAME ?? ""} / ${r.USER_NAME ?? ""}`,
        })));
      })
      .catch(() => setWorkerOptions([]));
  }, []);

  return (
    <div>
      <h2 className="text-lg font-bold text-gray-800 mb-4">작업관리 현황</h2>

      <div className="inline-flex bg-gray-100 rounded-lg p-1 mb-4">
        <TabButton active={tab === "project"} onClick={() => setTab("project")} label="프로젝트 작업현황" />
        <TabButton active={tab === "employee"} onClick={() => setTab("employee")} label="담당자별 작업현황" />
      </div>

      {tab === "project" ? (
        <ProjectTab projectOptions={projectOptions} />
      ) : (
        <EmployeeTab projectOptions={projectOptions} deptOptions={deptOptions} workerOptions={workerOptions} />
      )}
    </div>
  );
}

function TabButton({ active, onClick, label }: { active: boolean; onClick: () => void; label: string }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`px-4 py-1.5 rounded-md text-sm font-medium transition-colors ${
        active ? "bg-white text-primary shadow-sm" : "text-gray-500 hover:text-gray-700"
      }`}
    >
      {label}
    </button>
  );
}

// ── 프로젝트 작업현황 ────────────────────────────────────────
function ProjectTab({ projectOptions }: { projectOptions: Option[] }) {
  const [projectObjId, setProjectObjId] = useState("");
  const [unitCode, setUnitCode] = useState("");
  const [unitOptions, setUnitOptions] = useState<Option[]>([]);
  const [rows, setRows] = useState<Record<string, unknown>[]>([]);
  const [sumMap, setSumMap] = useState<ProjectSumMap>({});

  const handleProjectChange = useCallback((next: string) => {
    setProjectObjId(next);
    setUnitCode("");
    if (!next) { setUnitOptions([]); return; }
    fetch("/api/common/unit-list", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ contract_objid: next }),
    })
      .then((r) => r.json())
      .then((d) => {
        const list = (d.RESULTLIST || []) as Record<string, unknown>[];
        setUnitOptions(list.map((r) => ({
          value: String(r.OBJID ?? ""),
          label: String(r.UNIT_NAME ?? ""),
        })));
      })
      .catch(() => setUnitOptions([]));
  }, []);

  const fetchData = useCallback(async () => {
    if (!projectObjId) {
      Swal.fire("알림", "프로젝트번호는 필수값입니다.", "warning");
      return;
    }
    const res = await fetch("/api/work/status/project", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ project_nos: [projectObjId], unit_code: unitCode }),
    });
    if (res.ok) {
      const json = await res.json();
      setRows(json.RESULTLIST || []);
      setSumMap(json.SUM_PRICE_MAP || {});
    }
  }, [projectObjId, unitCode]);

  const columns: GridColumn[] = [
    {
      title: "프로젝트", headerHozAlign: "center",
      columns: [
        { title: "프로젝트번호", field: "PROJECT_NO", width: 140, hozAlign: "left" },
        { title: "유닛명", field: "UNIT_NAME", width: 200, hozAlign: "left" },
      ],
    },
    {
      title: "투입공수", headerHozAlign: "center",
      columns: [
        { title: "영업", field: "SALES_INPUT", width: 80, hozAlign: "right", formatter: "money" },
        { title: "관리", field: "MGMT_INPUT", width: 80, hozAlign: "right", formatter: "money" },
        { title: "설계", field: "DESIGN_INPUT", width: 80, hozAlign: "right", formatter: "money" },
        { title: "구매", field: "PURCHASE_INPUT", width: 80, hozAlign: "right", formatter: "money" },
        { title: "생관", field: "PRODUCTION_MGMT_INPUT", width: 80, hozAlign: "right", formatter: "money" },
        { title: "생산", field: "PRODUCTION_INPUT", width: 80, hozAlign: "right", formatter: "money" },
        { title: "외주", field: "OUTSOURCING", width: 80, hozAlign: "right", formatter: "money" },
        { title: "작업시간(h)", field: "WORK_HOUR", width: 110, hozAlign: "right", formatter: "money" },
        { title: "Day/Man", field: "MAN_DAY", width: 90, hozAlign: "right", formatter: "money" },
        { title: "Month/Man", field: "MAN_MONTH", width: 100, hozAlign: "right", formatter: "money" },
      ],
    },
  ];

  return (
    <>
      <SearchForm onSearch={fetchData}>
        <SearchField label="프로젝트번호">
          <SearchableSelect
            options={projectOptions}
            value={projectObjId}
            onChange={handleProjectChange}
            className="w-[280px]"
            placeholder="선택"
          />
        </SearchField>
        <SearchField label="유닛명">
          <SearchableSelect
            options={unitOptions}
            value={unitCode}
            onChange={setUnitCode}
            className="w-[240px]"
            placeholder="선택"
            disabled={!projectObjId}
          />
        </SearchField>
      </SearchForm>

      <div className="flex justify-end gap-2 mb-3">
        <Button size="sm" variant="secondary" onClick={fetchData}>조회</Button>
      </div>

      <DataGrid columns={columns} data={rows} />

      {/* 합계 */}
      {rows.length > 0 && (
        <div className="mt-2 border border-gray-200 rounded bg-gray-50 px-3 py-2 text-xs text-gray-700">
          <span className="font-semibold mr-4">(계)</span>
          <SumCell label="영업" value={sumMap.SUM_SALES_INPUT} />
          <SumCell label="관리" value={sumMap.SUM_MGMT_INPUT} />
          <SumCell label="설계" value={sumMap.SUM_DESIGN_INPUT} />
          <SumCell label="구매" value={sumMap.SUM_PURCHASE_INPUT} />
          <SumCell label="생관" value={sumMap.SUM_PRODUCTION_MGMT_INPUT} />
          <SumCell label="생산" value={sumMap.SUM_PRODUCTION_INPUT} />
          <SumCell label="외주" value={sumMap.SUM_OUTSOURCING} />
          <SumCell label="작업시간" value={sumMap.SUM_WORK_HOUR} />
          <SumCell label="Day/Man" value={sumMap.SUM_MAN_DAY} />
          <SumCell label="Month/Man" value={sumMap.SUM_MAN_MONTH} />
        </div>
      )}
    </>
  );
}

// ── 담당자별 작업현황 ────────────────────────────────────────
function EmployeeTab({ projectOptions, deptOptions, workerOptions }: {
  projectOptions: Option[]; deptOptions: Option[]; workerOptions: Option[];
}) {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [projectObjId, setProjectObjId] = useState("");
  const [deptCode, setDeptCode] = useState("");
  const [worker, setWorker] = useState("");
  const [list, setList] = useState<Record<string, unknown>[]>([]);
  const [npList, setNpList] = useState<Record<string, unknown>[]>([]);
  const [sumMap, setSumMap] = useState<EmployeeSumMap>({});

  // 부서 선택 시 작업자 목록 필터링
  const filteredWorkers = useMemo(() => {
    if (!deptCode) return workerOptions;
    // user-list 옵션 label을 '부서명 / 작업자'로 구성하므로 간단 필터링 불가 → 전체 재요청 생략
    return workerOptions;
  }, [deptCode, workerOptions]);

  const fetchData = useCallback(async () => {
    if (!deptCode && !worker) {
      Swal.fire("알림", "팀명 또는 작업자는 필수값입니다.", "warning");
      return;
    }
    const res = await fetch("/api/work/status/employee", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year,
        project_nos: projectObjId ? [projectObjId] : [],
        busUsersDeptId: deptCode,
        worker,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setList(json.LIST || []);
      setNpList(json.NP_LIST || []);
      setSumMap(json.SUM_PRICE_MAP || {});
    }
  }, [year, projectObjId, deptCode, worker]);

  // 합쳐서 그리드에 표시: 프로젝트 행 + 합계 구분행 + 비프로젝트 행
  const combined = useMemo(() => {
    const projectRows = list.map((r) => ({ ...r, _DIVISION: "프로젝트" }));
    const npRows = npList.map((r) => ({ ...r, _DIVISION: "비프로젝트", PROJECT_NO: "" }));
    return [...projectRows, ...npRows];
  }, [list, npList]);

  const columns: GridColumn[] = [
    { title: "구분", field: "_DIVISION", width: 100, hozAlign: "left" },
    { title: "프로젝트번호", field: "PROJECT_NO", width: 140, hozAlign: "left" },
    { title: "팀명", field: "WORKER_DEPT_NAME", width: 120, hozAlign: "center" },
    { title: "작업자", field: "WORKER_USER_NAME", width: 120, hozAlign: "center" },
    { title: "작업시간", field: "WORK_HOUR", width: 100, hozAlign: "right", formatter: "money" },
    { title: "Day/Man", field: "MAN_DAY", width: 100, hozAlign: "right", formatter: "money" },
    { title: "Month/Man", field: "MAN_MONTH", width: 110, hozAlign: "right", formatter: "money" },
  ];

  return (
    <>
      <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">
            {Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - i).map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
        </SearchField>
        <SearchField label="프로젝트번호">
          <SearchableSelect
            options={projectOptions}
            value={projectObjId}
            onChange={setProjectObjId}
            className="w-[260px]"
            placeholder="선택"
          />
        </SearchField>
        <SearchField label="팀명">
          <SearchableSelect
            options={deptOptions}
            value={deptCode}
            onChange={setDeptCode}
            className="w-[180px]"
            placeholder="선택"
          />
        </SearchField>
        <SearchField label="작업자">
          <SearchableSelect
            options={filteredWorkers}
            value={worker}
            onChange={setWorker}
            className="w-[220px]"
            placeholder="선택"
          />
        </SearchField>
      </SearchForm>

      <div className="flex justify-end gap-2 mb-3">
        <Button size="sm" variant="secondary" onClick={fetchData}>조회</Button>
      </div>

      <DataGrid columns={columns} data={combined} />

      {/* 프로젝트 합계 */}
      {list.length > 0 && (
        <div className="mt-2 border border-gray-200 rounded bg-gray-50 px-3 py-2 text-xs text-gray-700">
          <span className="font-semibold mr-4">프로젝트 합계</span>
          <SumCell label="작업시간" value={sumMap.SUM_WORK_HOUR} />
          <SumCell label="Day/Man" value={sumMap.SUM_MAN_DAY} />
          <SumCell label="Month/Man" value={sumMap.SUM_MAN_MONTH} />
        </div>
      )}
    </>
  );
}

function SumCell({ label, value }: { label: string; value?: number }) {
  return (
    <span className="inline-block mr-5">
      <span className="text-gray-500">{label}:</span>{" "}
      <span className="font-semibold">{numberWithCommas(Number(value) || 0)}</span>
    </span>
  );
}
