'use client';

import { useState } from "react";
import { useRouter } from "next/navigation";
import ModalCloseSvg from "../svgs/closexsvg";
import apiService from "../lib/apiService";

type Props = {
  open: boolean;
  onClose: () => void;
  onConfirm?: () => void;
};

export default function AccountDeleteModal({ open, onClose, onConfirm }: Props) {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);

  const handleConfirm = async () => {
    if (onConfirm) {
      onConfirm();
      return;
    }

    setIsLoading(true);
    try {
      await apiService.deleteAccount();

      // 성공 시 토큰 제거 및 로그인 페이지로 이동
      localStorage.removeItem('token');
      onClose();
      router.push('/login');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '네트워크 오류가 발생했습니다.';
      console.error('회원 탈퇴 오류:', errorMessage);
      alert(errorMessage);
      setIsLoading(false);
    }
  };

  if (!open) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[2px]"
      role="dialog"
      aria-modal="true"
    >
      <div className="w-[528px] rounded-[12px] border border-[#dee1e6] bg-white shadow-[0_10px_30px_rgba(0,0,0,0.06)]">
        {/* header */}
        <div className="flex items-center justify-between p-6">
          <h2 className="text-[20px] font-bold leading-normal text-[#333c47]">회원 탈퇴</h2>
          <button
            type="button"
            aria-label="닫기"
            onClick={onClose}
            className="inline-flex size-6 items-center justify-center text-[#333c47] hover:opacity-80 cursor-pointer"
          >
            <ModalCloseSvg />
          </button>
        </div>

        {/* body */}
        <div className="px-6">
          <div className="rounded-[16px] border border-[#dee1e6] bg-gray-50 p-6">
            <p className="mb-3 text-[15px] font-bold leading-normal text-basic-text">
              회원 탈퇴 시 유의사항을 확인해주세요.
            </p>
            <div className="text-[15px] leading-normal text-basic-text">
              <p className="mb-0">- 탈퇴 후에도 재가입은 가능합니다.</p>
              <p className="mb-0">- 수강 및 학습 이력이 모두 삭제되며, 복구가 불가능합니다.</p>
              <p>- 수강 서비스 이용 권한이 즉시 종료됩니다.</p>
            </div>
          </div>
        </div>

        {/* footer */}
        <div className="flex items-center justify-center gap-3 p-6">
          <button
            type="button"
            onClick={onClose}
            className="h-12 w-[136px] rounded-[10px] bg-[#f1f3f5] px-4 text-[16px] font-semibold leading-normal text-basic-text cursor-pointer"
          >
            취소
          </button>
          <button
            type="button"
            onClick={handleConfirm}
            disabled={isLoading}
            className="h-12 w-[136px] rounded-[10px] bg-red-50 px-4 text-[16px] font-semibold leading-normal text-error cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isLoading ? '처리 중...' : '회원 탈퇴'}
          </button>
        </div>
      </div>
    </div>
  );
}


