"use client";

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

// productionplanning/workDiaryList.jsp 대응 - 작업일지 목록
interface Option { value: string; label: string }

export default function WorkDiaryPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [searchDivision, setSearchDivision] = useState("");
  const [projectObjId, setProjectObjId] = useState("");
  const [unitCode, setUnitCode] = useState("");
  const [deptCode, setDeptCode] = useState("");
  const [worker, setWorker] = useState("");
  const [searchStatus, setSearchStatus] = useState("");

  const [projectOptions, setProjectOptions] = useState<Option[]>([]);
  const [unitOptions, setUnitOptions] = useState<Option[]>([]);
  const [deptOptions, setDeptOptions] = useState<Option[]>([]);
  const [workerOptions, setWorkerOptions] = useState<Option[]>([]);

  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);

  // 공용 드롭다운
  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([]));
  }, []);

  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 () => {
    const res = await fetch("/api/work/diary", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year,
        search_division: searchDivision,
        project_nos: projectObjId ? [projectObjId] : [],
        unit_code: unitCode,
        busUsersDeptId: deptCode,
        worker,
        search_status: searchStatus,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [year, searchDivision, projectObjId, unitCode, deptCode, worker, searchStatus]);

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

  const openFormPopup = (objId?: string) => {
    const w = 1200; const h = 600;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    const url = objId ? `/work/diary/form?objId=${encodeURIComponent(objId)}` : "/work/diary/form";
    window.open(url, "diaryForm", `width=${w},height=${h},left=${left},top=${top}`);
  };

  const collectWriteIds = () => selectedRows
    .filter((r) => r.STATUS === "write")
    .map((r) => String(r.OBJID));

  const handleDelete = async () => {
    if (selectedRows.length === 0) { Swal.fire("알림", "선택된 데이터가 없습니다.", "warning"); return; }
    const ids = collectWriteIds();
    if (ids.length === 0) { Swal.fire("알림", "작성중인 데이터만 삭제 가능합니다.", "warning"); return; }

    const confirm = await Swal.fire({
      title: "선택된 데이터를 삭제 하시겠습니까?",
      icon: "warning", showCancelButton: true,
      confirmButtonText: "확인", cancelButtonText: "취소",
    });
    if (!confirm.isConfirmed) return;

    const res = await fetch("/api/work/diary/delete", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ checkArr: ids }),
    });
    const json = await res.json();
    await Swal.fire(json.msg || (json.success ? "삭제되었습니다." : "삭제 실패"), "", json.success ? "success" : "error");
    if (json.success) fetchData();
  };

  const handleConfirm = async () => {
    if (selectedRows.length === 0) { Swal.fire("알림", "선택된 데이터가 없습니다.", "warning"); return; }
    const ids = collectWriteIds();
    if (ids.length === 0) { Swal.fire("알림", "등록중인 데이터만 배포 가능합니다.", "warning"); return; }

    const confirm = await Swal.fire({
      title: "선택된 데이터를 확정 하시겠습니까?",
      icon: "warning", showCancelButton: true,
      confirmButtonText: "확인", cancelButtonText: "취소",
    });
    if (!confirm.isConfirmed) return;

    const res = await fetch("/api/work/diary/confirm", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ checkArr: ids }),
    });
    const json = await res.json();
    await Swal.fire(json.msg || (json.success ? "확정되었습니다." : "확정 실패"), "", json.success ? "success" : "error");
    if (json.success) fetchData();
  };

  const columns: GridColumn[] = [
    {
      title: "구분", field: "DIVISION", width: 110, hozAlign: "center",
      formatter: (v) => v === "project" ? "프로젝트" : v === "non_project" ? "비프로젝트" : String(v ?? ""),
      cellClick: (row) => openFormPopup(String(row.OBJID)),
    },
    { title: "프로젝트번호", field: "PROJECT_NO", width: 130, hozAlign: "left" },
    { title: "유닛명", field: "UNIT_CODE_NAME", width: 260, hozAlign: "left" },
    { title: "TASK명", field: "TASK_NAME", width: 320, hozAlign: "left" },
    { title: "팀명", field: "DEPT_NAME", width: 110, hozAlign: "center" },
    { title: "작업자", field: "WORKER_NAME", width: 110, hozAlign: "center" },
    { title: "작업시작일", field: "WORK_START_DATE", width: 110, hozAlign: "center" },
    { title: "작업종료일", field: "WORK_END_DATE", width: 110, hozAlign: "center" },
    { title: "작업시간", field: "WORK_HOUR", width: 90, hozAlign: "right", formatter: "money" },
    { title: "상태", field: "STATUS_TITLE", width: 90, 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={handleDelete}>삭제</Button>
          <Button size="sm" onClick={() => openFormPopup()}>작업일지등록</Button>
          <Button size="sm" variant="secondary" onClick={handleConfirm}>팀장확인</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="구분">
          <select value={searchDivision} onChange={(e) => setSearchDivision(e.target.value)}
            className="h-9 w-[130px] rounded border border-gray-300 bg-white px-3 text-sm">
            <option value="">선택</option>
            <option value="project">프로젝트</option>
            <option value="non_project">비프로젝트</option>
          </select>
        </SearchField>
        <SearchField label="프로젝트번호">
          <SearchableSelect options={projectOptions} value={projectObjId} onChange={handleProjectChange}
            className="w-[240px]" placeholder="선택" />
        </SearchField>
        <SearchField label="유닛명">
          <SearchableSelect options={unitOptions} value={unitCode} onChange={setUnitCode}
            className="w-[200px]" placeholder="선택" disabled={!projectObjId} />
        </SearchField>
        <SearchField label="팀명">
          <SearchableSelect options={deptOptions} value={deptCode} onChange={setDeptCode}
            className="w-[160px]" placeholder="선택" />
        </SearchField>
        <SearchField label="작업자">
          <SearchableSelect options={workerOptions} value={worker} onChange={setWorker}
            className="w-[200px]" placeholder="선택" />
        </SearchField>
        <SearchField label="상태">
          <select value={searchStatus} onChange={(e) => setSearchStatus(e.target.value)}
            className="h-9 w-[130px] rounded border border-gray-300 bg-white px-3 text-sm">
            <option value="">선택</option>
            <option value="write">작성중</option>
            <option value="complete">확인완료</option>
          </select>
        </SearchField>
      </SearchForm>

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

      />
    </div>
  );
}
