"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import Swal from "sweetalert2";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";

type ApprovalType = "normal" | "help" | "ref";

interface Approver {
  user_id: string;
  user_name: string;
  dept_name: string;
  position_name?: string;
  approval_type: ApprovalType;
}

interface UserOption {
  USER_ID: string;
  USER_NAME: string;
  DEPT_NAME?: string;
  POSITION_NAME?: string;
}

export interface ApprovalRequestModalProps {
  open: boolean;
  onClose: () => void;
  objIds: string[];         // 결재할 대상 OBJID 배열 (다건 상신 지원)
  targetType: string;       // PURCHASE_ORDER | CSM | EXPENSE_APPLY | EO_MNG ...
  defaultTitle?: string;
  defaultDescription?: string;
  onSuccess?: () => void;   // 상신 성공 시 목록 리프레시 등
  systemType?: string;
}

// registApproval.jsp 대응 - 결재 상신 모달 (일반/협조/참조 + 전자서명 없이 상신만)
export function ApprovalRequestModal({
  open, onClose, objIds, targetType,
  defaultTitle = "", defaultDescription = "",
  onSuccess, systemType = "PLM",
}: ApprovalRequestModalProps) {
  const [mounted, setMounted] = useState(false);
  const [title, setTitle] = useState(defaultTitle);
  const [description, setDescription] = useState(defaultDescription);
  const [searchDept, setSearchDept] = useState("");
  const [searchUser, setSearchUser] = useState("");
  const [users, setUsers] = useState<UserOption[]>([]);
  const [approvers, setApprovers] = useState<Approver[]>([]);
  const [activeType, setActiveType] = useState<ApprovalType>("normal");
  const [submitting, setSubmitting] = useState(false);
  const initRef = useRef(false);

  useEffect(() => { setMounted(true); }, []);

  // 모달 열릴 때 초기화
  useEffect(() => {
    if (!open) { initRef.current = false; return; }
    if (initRef.current) return;
    initRef.current = true;
    setTitle(defaultTitle);
    setDescription(defaultDescription);
    setApprovers([]);
    setSearchDept("");
    setSearchUser("");
    // 사용자 목록 초기 로드
    fetchUsers();
  }, [open, defaultTitle, defaultDescription]);

  const fetchUsers = async () => {
    try {
      const res = await fetch("/api/admin/users", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ dept_name: searchDept, user_name: searchUser }),
      });
      const j = await res.json();
      setUsers((j.RESULTLIST || []) as UserOption[]);
    } catch { setUsers([]); }
  };

  const filteredUsers = useMemo(() => {
    const d = searchDept.toLowerCase();
    const u = searchUser.toLowerCase();
    return users.filter((x) =>
      (!d || (x.DEPT_NAME || "").toLowerCase().includes(d)) &&
      (!u || (x.USER_NAME || "").toLowerCase().includes(u))
    );
  }, [users, searchDept, searchUser]);

  const addApprover = (u: UserOption) => {
    if (approvers.some((a) => a.user_id === u.USER_ID && a.approval_type === activeType)) {
      Swal.fire("알림", "동일한 사원이 이미 해당 결재선에 있습니다.", "info");
      return;
    }
    setApprovers((prev) => [
      ...prev,
      {
        user_id: u.USER_ID,
        user_name: u.USER_NAME,
        dept_name: u.DEPT_NAME || "",
        position_name: u.POSITION_NAME || "",
        approval_type: activeType,
      },
    ]);
  };

  const removeApprover = (idx: number) => {
    setApprovers((prev) => prev.filter((_, i) => i !== idx));
  };

  const moveApprover = (idx: number, dir: -1 | 1) => {
    setApprovers((prev) => {
      const next = [...prev];
      const swap = idx + dir;
      if (swap < 0 || swap >= next.length) return prev;
      // 같은 타입 내에서만 순서 변경
      if (next[idx].approval_type !== next[swap].approval_type) return prev;
      [next[idx], next[swap]] = [next[swap], next[idx]];
      return next;
    });
  };

  const byType = (t: ApprovalType) => approvers.filter((a) => a.approval_type === t);

  const handleSubmit = async () => {
    if (!title.trim()) { Swal.fire("알림", "결재 제목을 입력하세요.", "warning"); return; }
    if (byType("normal").length === 0) {
      Swal.fire("알림", "일반 결재선을 1명 이상 지정하세요.", "warning"); return;
    }
    if (objIds.length === 0) {
      Swal.fire("알림", "결재 대상이 없습니다.", "warning"); return;
    }

    const r = await Swal.fire({
      title: "결재 상신", text: `${objIds.length}건을 상신합니다. 진행할까요?`,
      icon: "question", showCancelButton: true,
      confirmButtonText: "상신", cancelButtonText: "취소",
    });
    if (!r.isConfirmed) return;

    setSubmitting(true);
    let ok = 0, fail = 0;
    try {
      for (const targetObjId of objIds) {
        try {
          const res = await fetch("/api/approval/request", {
            method: "POST", headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              target_objid: targetObjId,
              target_type: targetType,
              approval_title: title,
              approval_desc: description,
              system_type: systemType,
              approvers: approvers.map((a) => ({ user_id: a.user_id, approval_type: a.approval_type })),
            }),
          });
          const j = await res.json();
          if (j.success) ok++; else fail++;
        } catch { fail++; }
      }
    } finally { setSubmitting(false); }

    if (fail === 0) {
      await Swal.fire({ icon: "success", title: `${ok}건 결재 상신되었습니다.`, timer: 1200, showConfirmButton: false });
      onSuccess?.();
      onClose();
    } else {
      await Swal.fire("부분 실패", `성공 ${ok}건 / 실패 ${fail}건`, "warning");
      if (ok > 0) { onSuccess?.(); onClose(); }
    }
  };

  if (!open || !mounted || typeof document === "undefined") return null;

  return createPortal(
    <div className="fixed inset-0 z-[9999] flex items-center justify-center">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative bg-white rounded-lg shadow-2xl w-[860px] max-h-[88vh] overflow-hidden flex flex-col">
        {/* 헤더 */}
        <div className="flex items-center justify-between border-b px-4 py-2.5 bg-gray-50">
          <h3 className="font-semibold text-gray-800">결재 상신 {objIds.length > 1 && <span className="text-xs text-blue-600 ml-2">({objIds.length}건 동시 상신)</span>}</h3>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-700 text-lg">×</button>
        </div>

        <div className="flex-1 overflow-auto p-4 grid grid-cols-2 gap-4">
          {/* 좌: 결재내용 + 사원검색 */}
          <div className="space-y-2">
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">결재 번호</label>
              <Input value="결재 상신 후 자동생성됩니다." readOnly disabled className="bg-gray-50" />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">제목 <span className="text-red-500">*</span></label>
              <Input value={title} onChange={(e) => setTitle(e.target.value)} maxLength={256} />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">내용</label>
              <Input value={description} onChange={(e) => setDescription(e.target.value)} maxLength={256} />
            </div>

            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">결재 Type</label>
              <div className="flex gap-3 text-sm">
                {(["normal", "help", "ref"] as ApprovalType[]).map((t) => (
                  <label key={t} className="flex items-center gap-1 cursor-pointer">
                    <input type="radio" checked={activeType === t} onChange={() => setActiveType(t)} />
                    <span>{t === "normal" ? "일반" : t === "help" ? "협조" : "참조"}</span>
                  </label>
                ))}
              </div>
            </div>

            <div className="grid grid-cols-3 gap-2 items-end">
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">부서</label>
                <Input value={searchDept} onChange={(e) => setSearchDept(e.target.value)}
                  onKeyUp={(e) => e.key === "Enter" && fetchUsers()} />
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">성명</label>
                <Input value={searchUser} onChange={(e) => setSearchUser(e.target.value)}
                  onKeyUp={(e) => e.key === "Enter" && fetchUsers()} />
              </div>
              <Button size="sm" onClick={fetchUsers}>조회</Button>
            </div>

            <div className="border border-gray-300 rounded overflow-hidden">
              <div className="bg-blue-50 px-2 py-1 text-xs font-semibold text-gray-700">사원조회 ({filteredUsers.length}명)</div>
              <div className="max-h-[220px] overflow-auto">
                <table className="w-full text-xs">
                  <thead className="bg-gray-50 sticky top-0">
                    <tr>
                      <th className="px-2 py-1 text-left">부서</th>
                      <th className="px-2 py-1 text-left">이름</th>
                      <th className="px-2 py-1 text-left">직책</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredUsers.length === 0 ? (
                      <tr><td colSpan={3} className="text-center text-gray-400 py-3">조회된 정보가 없습니다.</td></tr>
                    ) : filteredUsers.map((u) => (
                      <tr key={u.USER_ID} className="hover:bg-blue-50 cursor-pointer" onClick={() => addApprover(u)}>
                        <td className="px-2 py-1 border-t">{u.DEPT_NAME || "-"}</td>
                        <td className="px-2 py-1 border-t">{u.USER_NAME}</td>
                        <td className="px-2 py-1 border-t">{u.POSITION_NAME || "-"}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>

          {/* 우: 결재선 */}
          <div className="space-y-3">
            {(["normal", "help", "ref"] as ApprovalType[]).map((t) => (
              <div key={t}>
                <div className="text-xs font-bold text-gray-700 mb-1">
                  {t === "normal" ? "일반 결재" : t === "help" ? "협조 결재" : "참조 결재"}
                  {t === "normal" && <span className="text-red-500 ml-1">*</span>}
                </div>
                <div className="border border-gray-300 rounded overflow-hidden">
                  <table className="w-full text-xs">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="w-10 px-2 py-1 text-center">순서</th>
                        <th className="px-2 py-1 text-left">부서</th>
                        <th className="px-2 py-1 text-left">이름</th>
                        <th className="px-2 py-1 text-left">직책</th>
                        <th className="w-24 px-2 py-1 text-center">이동/삭제</th>
                      </tr>
                    </thead>
                    <tbody>
                      {byType(t).length === 0 ? (
                        <tr><td colSpan={5} className="text-center text-gray-400 py-3">결재선이 비어있습니다. 좌측 사원목록 클릭으로 추가</td></tr>
                      ) : (
                        byType(t).map((a, localIdx) => {
                          // 전체 approvers 에서의 실제 인덱스
                          const realIdx = approvers.findIndex(
                            (x, i) => i >= 0 && x === a && approvers.slice(0, i).filter((y) => y.approval_type === t).length === localIdx
                          );
                          return (
                            <tr key={`${a.user_id}-${localIdx}`}>
                              <td className="px-2 py-1 border-t text-center">{localIdx + 1}</td>
                              <td className="px-2 py-1 border-t">{a.dept_name || "-"}</td>
                              <td className="px-2 py-1 border-t">{a.user_name}</td>
                              <td className="px-2 py-1 border-t">{a.position_name || "-"}</td>
                              <td className="px-2 py-1 border-t text-center whitespace-nowrap">
                                {t === "normal" && (
                                  <>
                                    <button className="text-gray-500 hover:text-gray-700 px-1" onClick={() => moveApprover(realIdx, -1)} disabled={localIdx === 0}>▲</button>
                                    <button className="text-gray-500 hover:text-gray-700 px-1" onClick={() => moveApprover(realIdx, 1)} disabled={localIdx === byType(t).length - 1}>▼</button>
                                  </>
                                )}
                                <button className="text-red-500 hover:text-red-700 px-1" onClick={() => removeApprover(realIdx)}>×</button>
                              </td>
                            </tr>
                          );
                        })
                      )}
                    </tbody>
                  </table>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 푸터 */}
        <div className="flex justify-center gap-2 border-t px-4 py-3 bg-gray-50">
          <Button onClick={handleSubmit} disabled={submitting}>{submitting ? "상신 중..." : "상신"}</Button>
          <Button variant="secondary" onClick={onClose} disabled={submitting}>닫기</Button>
        </div>
      </div>
    </div>,
    document.body
  );
}
