"use client";

import { useState, useEffect, Suspense } from "react";
import { useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import Swal from "sweetalert2";

function UserForm() {
  const searchParams = useSearchParams();
  const userId = searchParams.get("userId");
  const isNew = !userId;
  const [form, setForm] = useState<Record<string, string>>({});
  const [depts, setDepts] = useState<{ dept_code: string; dept_name: string }[]>([]);
  const [loading, setLoading] = useState(false);
  const set = (k: string, v: string) => setForm((p) => ({ ...p, [k]: v }));

  useEffect(() => {
    fetch("/api/admin/dept", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })
      .then((r) => r.json()).then((d) => setDepts(d.RESULTLIST || [])).catch(() => {});
  }, []);

  useEffect(() => {
    if (userId) {
      fetch("/api/admin/users/detail", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId }),
      }).then((r) => r.json()).then((d) => { if (d.success) setForm(d.data); }).catch(() => {});
    }
  }, [userId]);

  const handleSave = async () => {
    if (!form.user_id) { Swal.fire("알림", "사용자 ID를 입력하세요.", "warning"); return; }
    if (!form.user_name) { Swal.fire("알림", "이름을 입력하세요.", "warning"); return; }
    setLoading(true);
    try {
      const res = await fetch("/api/admin/users/save", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...form, actionType: isNew ? "regist" : "update" }),
      });
      const data = await res.json();
      if (data.success) {
        await Swal.fire({ icon: "success", title: data.message || "저장되었습니다.", timer: 1500, showConfirmButton: false });
        if (window.opener) try { window.opener.location.reload(); } catch {}
        if (isNew) window.close();
      } else { Swal.fire("오류", data.message || "저장 실패", "error"); }
    } catch { Swal.fire("오류", "서버 오류", "error"); }
    finally { setLoading(false); }
  };

  return (
    <div className="p-5 bg-white min-h-screen">
      <h2 className="text-base font-bold text-gray-800 mb-4 border-b pb-2">
        {isNew ? "사용자 등록" : `사용자 수정 (${userId})`}
      </h2>
      <div className="grid grid-cols-2 gap-x-4 gap-y-3 text-sm">
        <div><label className="block text-xs font-medium text-gray-500 mb-1">사용자 ID <span className="text-red-400">*</span></label>
          <Input value={form.user_id || ""} onChange={(e) => set("user_id", e.target.value)} readOnly={!isNew} /></div>
        <div><label className="block text-xs font-medium text-gray-500 mb-1">이름 <span className="text-red-400">*</span></label>
          <Input value={form.user_name || ""} onChange={(e) => set("user_name", e.target.value)} /></div>
        <div><label className="block text-xs font-medium text-gray-500 mb-1">사번</label>
          <Input value={form.sabun || ""} onChange={(e) => set("sabun", e.target.value)} /></div>
        <div><label className="block text-xs font-medium text-gray-500 mb-1">부서</label>
          <select value={form.dept_code || ""} onChange={(e) => { set("dept_code", e.target.value); const d = depts.find((x) => x.dept_code === e.target.value); if (d) set("dept_name", d.dept_name); }}
            className="h-9 w-full rounded border border-gray-300 bg-white px-2 text-sm">
            <option value="">선택</option>
            {depts.map((d) => <option key={d.dept_code} value={d.dept_code}>{d.dept_name}</option>)}
          </select></div>
        <div><label className="block text-xs font-medium text-gray-500 mb-1">직급</label>
          <Input value={form.position_name || ""} onChange={(e) => set("position_name", e.target.value)} /></div>
        <div><label className="block text-xs font-medium text-gray-500 mb-1">이메일</label>
          <Input type="email" value={form.email || ""} onChange={(e) => set("email", e.target.value)} /></div>
        <div><label className="block text-xs font-medium text-gray-500 mb-1">전화번호</label>
          <Input value={form.cell_phone || ""} onChange={(e) => set("cell_phone", e.target.value)} /></div>
        <div><label className="block text-xs font-medium text-gray-500 mb-1">유형</label>
          <select value={form.user_type || ""} onChange={(e) => set("user_type", e.target.value)}
            className="h-9 w-full rounded border border-gray-300 bg-white px-2 text-sm">
            <option value="">선택</option>
            <option value="A">관리자</option>
            <option value="U">사용자</option>
            <option value="P">협력사</option>
          </select></div>
        {isNew && (
          <div className="col-span-2"><label className="block text-xs font-medium text-gray-500 mb-1">초기 비밀번호</label>
            <Input type="password" value={form.password || ""} onChange={(e) => set("password", e.target.value)} placeholder="비밀번호 입력" /></div>
        )}
      </div>
      <div className="flex justify-end gap-2 mt-6 pt-4 border-t">
        <Button onClick={handleSave} disabled={loading}>{loading ? "저장 중..." : "저장"}</Button>
        <Button variant="secondary" onClick={() => window.close()}>닫기</Button>
      </div>
    </div>
  );
}

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