"use client";

import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import Swal from "sweetalert2";
import { Button } from "@/components/ui/button";
import { SignaturePad, type SignaturePadHandle } from "./SignaturePad";

export interface ApprovalDecisionModalProps {
  open: boolean;
  onClose: () => void;
  inboxObjId: string;
  targetType?: string;
  requireSign?: boolean;      // 기본 true - invoice 등 사인 강제 케이스 대응
  onSuccess?: () => void;
}

// approvalDetailResultPopup.jsp 대응 - 결재 승인/반려 처리 모달 + 전자사인
export function ApprovalDecisionModal({
  open, onClose, inboxObjId, targetType, requireSign = true, onSuccess,
}: ApprovalDecisionModalProps) {
  const [result, setResult] = useState<"Y" | "N">("Y");
  const [message, setMessage] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const signRef = useRef<SignaturePadHandle>(null);
  const [mounted, setMounted] = useState(false);

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

  useEffect(() => {
    if (!open) return;
    setResult("Y");
    setMessage("");
    signRef.current?.clear();
  }, [open]);

  const mustSign = requireSign || targetType === "INVOICE";

  const submit = async () => {
    if (message.length > 200) {
      Swal.fire("알림", "사유는 200자까지 입력 가능합니다.", "warning");
      return;
    }
    if (mustSign && !signRef.current?.isSigned()) {
      Swal.fire("알림", "사인을 해주세요.", "warning");
      return;
    }
    const resultText = result === "Y" ? "승인" : "반려";
    const r = await Swal.fire({
      title: `${resultText} 확인`, text: `${resultText} 처리 하시겠습니까?`,
      icon: "question", showCancelButton: true,
      confirmButtonText: resultText, cancelButtonText: "취소",
    });
    if (!r.isConfirmed) return;

    const sign = mustSign ? signRef.current?.toDataURL() : null;
    const { width, height } = signRef.current?.getDimensions() || { width: 0, height: 0 };
    const endpoint = result === "Y" ? "/api/approval/approve" : "/api/approval/reject";

    setSubmitting(true);
    try {
      const res = await fetch(endpoint, {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ inboxObjId, message, sign, sign_width: width, sign_height: height }),
      });
      const j = await res.json();
      if (j.success) {
        await Swal.fire({ icon: "success", title: j.message || "처리되었습니다.", timer: 1200, showConfirmButton: false });
        onSuccess?.();
        onClose();
      } else {
        Swal.fire("오류", j.message || "처리 실패", "error");
      }
    } catch {
      Swal.fire("오류", "서버 오류가 발생했습니다.", "error");
    } finally { setSubmitting(false); }
  };

  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-[560px] overflow-hidden">
        <div className="flex items-center justify-between border-b px-4 py-2.5 bg-gray-50">
          <h3 className="font-semibold text-gray-800">결재 승인/반려 처리</h3>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-700 text-lg">×</button>
        </div>
        <div className="p-4 space-y-3 text-sm">
          <div>
            <label className="block text-xs font-semibold text-gray-600 mb-1">결과</label>
            <select
              value={result}
              onChange={(e) => setResult(e.target.value as "Y" | "N")}
              className="h-9 w-40 rounded border border-gray-300 bg-white px-3 text-sm"
            >
              <option value="Y">승인</option>
              <option value="N">반려</option>
            </select>
          </div>

          <div>
            <label className="block text-xs font-semibold text-gray-600 mb-1">사유</label>
            <textarea
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              rows={4}
              maxLength={200}
              className="w-full rounded border border-gray-300 px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/50"
              placeholder={result === "N" ? "반려 사유를 입력하세요." : "처리 사유를 입력하세요. (선택)"}
            />
            <div className="text-right text-xs text-gray-400">[{message.length}/200]</div>
          </div>

          {mustSign && (
            <div>
              <div className="flex justify-between items-end mb-1">
                <label className="text-xs font-semibold text-gray-600">사인 <span className="text-red-500">*</span></label>
                <button className="text-xs text-blue-600 hover:underline" onClick={() => signRef.current?.clear()}>
                  사인 Clear
                </button>
              </div>
              <SignaturePad ref={signRef} width={510} height={130} />
            </div>
          )}
        </div>
        <div className="flex justify-center gap-2 border-t px-4 py-3 bg-gray-50">
          <Button onClick={submit} disabled={submitting}>{submitting ? "저장 중..." : "저장"}</Button>
          <Button variant="secondary" onClick={onClose} disabled={submitting}>닫기</Button>
        </div>
      </div>
    </div>,
    document.body
  );
}
