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

// admin/adminUserList.jsp 대응 - 관리자 (사용자관리)
export default function AdminPage() {
  const [searchName, setSearchName] = useState("");
  const [searchDept, setSearchDept] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "사번", field: "SABUN", width: 100, hozAlign: "center" },
    { title: "아이디", field: "USER_ID", width: 120, hozAlign: "left",
      cellClick: (row) => window.open(`/admin/user-form?userId=${row.USER_ID}`, "userForm", "width=700,height=600") },
    { title: "이름", field: "USER_NAME", width: 100, hozAlign: "center" },
    { title: "부서", field: "DEPT_NAME", width: 120, hozAlign: "center" },
    { title: "직급", field: "POSITION_NAME", width: 80, hozAlign: "center" },
    { title: "이메일", field: "EMAIL", width: 180, hozAlign: "left" },
    { title: "연락처", field: "TEL", width: 130, hozAlign: "center" },
    { title: "유형", field: "USER_TYPE_NAME", width: 80, hozAlign: "center" },
    { title: "권한", field: "AUTH_NAME", width: 150, hozAlign: "left" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/admin/users", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ user_name: searchName, dept_name: searchDept }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [searchName, searchDept]);

  // 페이지 진입 시 자동 로드
  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={() => window.open("/admin/user-form", "userForm", "width=700,height=600")}>등록</Button>
          <Button size="sm" variant="secondary" onClick={fetchData}>조회</Button>
        </div>
      </div>
      <SearchForm onSearch={fetchData}>
        <SearchField label="이름">
          <Input value={searchName} onChange={(e) => setSearchName(e.target.value)} className="w-[120px]" />
        </SearchField>
        <SearchField label="부서">
          <Input value={searchDept} onChange={(e) => setSearchDept(e.target.value)} className="w-[120px]" />
        </SearchField>
      </SearchForm>
      <DataGrid columns={columns} data={data} />
    </div>
  );
}
