"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 { ApprovalStatusBadge } from "@/components/approval/ApprovalStatusBadge";
import { TARGET_NAME_MAP } from "@/components/approval/TargetLinkMap";
import { cn } from "@/lib/utils";

// approvalList.jsp 대응 - 결재함 (미결재/승인/반려/전체 탭)
type Tab = "PENDING" | "APPROVED" | "REJECTED" | "";

const TABS: { key: Tab; label: string }[] = [
  { key: "PENDING", label: "미결재" },
  { key: "APPROVED", label: "승인" },
  { key: "REJECTED", label: "반려" },
  { key: "", label: "전체" },
];

export default function ApprovalPage() {
  const [tab, setTab] = useState<Tab>("PENDING");
  const [title, setTitle] = useState("");
  const [writerName, setWriterName] = useState("");
  const [fromDate, setFromDate] = useState("");
  const [toDate, setToDate] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [loading, setLoading] = useState(false);

  const openDetail = (row: Record<string, unknown>) => {
    const w = 900, h = 700;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(`/approval/form?objId=${row.APPROVAL_OBJID || row.OBJID}`,
      "approvalDetail",
      `width=${w},height=${h},left=${left},top=${top}`);
  };

  const columns: GridColumn[] = [
    { title: "결재번호", field: "APPROVAL_NO", width: 110, hozAlign: "center" },
    {
      title: "대상구분", field: "TYPE_NAME", width: 120, hozAlign: "left",
      formatter: (_, row) => (TARGET_NAME_MAP[String(row.TARGET_TYPE)] || String(row.TYPE_NAME ?? row.TARGET_TYPE ?? "-")),
    },
    {
      title: "제목", field: "TITLE", width: 300, hozAlign: "left",
      cellClick: openDetail,
    },
    { title: "상신일", field: "REGDATE", width: 110, hozAlign: "center" },
    {
      title: "상신자", field: "WRITER_NAME", width: 180, hozAlign: "left",
      formatter: (_, row) => {
        const dept = row.DEPT_NAME ? String(row.DEPT_NAME) + " / " : "";
        return dept + String(row.WRITER_NAME ?? row.WRITER ?? "");
      },
    },
    {
      title: "상태", field: "STATUS_NAME", width: 100, hozAlign: "center",
      formatter: (_, row) => <ApprovalStatusBadge status={row.STATUS_NAME || row.APPROVAL_STATUS} />,
    },
  ];

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/approval", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          status: tab,
          title,
          writer_name: writerName,
          from_date: fromDate,
          to_date: toDate,
        }),
      });
      if (res.ok) {
        const json = await res.json();
        setData(json.RESULTLIST || []);
      }
    } finally { setLoading(false); }
  }, [tab, title, writerName, fromDate, toDate]);

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

  // 파일 업로드 팝업 등에서 refresh 콜백으로 쓸 수 있게 전역 등록
  useEffect(() => {
    (window as unknown as Record<string, unknown>).fn_search = fetchData;
    return () => { delete (window as unknown as Record<string, unknown>).fn_search; };
  }, [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" variant="secondary" onClick={fetchData}>조회</Button>
        </div>
      </div>

      {/* 탭 */}
      <div className="flex items-center border-b border-gray-200 mb-4">
        {TABS.map((t) => (
          <button
            key={t.key}
            onClick={() => setTab(t.key)}
            className={cn(
              "px-4 py-2 text-sm border-b-2 -mb-px transition-colors",
              tab === t.key
                ? "border-primary text-primary font-semibold"
                : "border-transparent text-gray-500 hover:text-gray-800"
            )}
          >
            {t.label}
          </button>
        ))}
      </div>

      <SearchForm onSearch={fetchData}>
        <SearchField label="제목">
          <Input value={title} onChange={(e) => setTitle(e.target.value)} className="w-[240px]" />
        </SearchField>
        <SearchField label="상신자">
          <Input value={writerName} onChange={(e) => setWriterName(e.target.value)} className="w-[150px]" />
        </SearchField>
        <SearchField label="상신일">
          <div className="flex items-center gap-1">
            <Input type="date" value={fromDate} onChange={(e) => setFromDate(e.target.value)} className="w-[140px]" />
            <span className="text-gray-400">~</span>
            <Input type="date" value={toDate} onChange={(e) => setToDate(e.target.value)} className="w-[140px]" />
          </div>
        </SearchField>
      </SearchForm>

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