'use client';

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import ChangePasswordModal from "../ChangePasswordModal";
import PasswordChangeDoneModal from "../PasswordChangeDoneModal";
import AccountDeleteModal from "../AccountDeleteModal";
import MenuAccountOption from "@/app/menu/account/MenuAccountOption";
import apiService from "@/app/lib/apiService";

type VerificationState = 'initial' | 'sent' | 'verified' | 'failed' | 'changed';

type UserInfo = {
  email?: string;
  name?: string;
  phone?: string;
};

export default function AccountPage() {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [verificationState, setVerificationState] = useState<VerificationState>('initial');
  const [doneOpen, setDoneOpen] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [userInfo, setUserInfo] = useState<UserInfo>({});
  const [isLoading, setIsLoading] = useState(true);

  // 페이지 로드 시 사용자 정보 가져오기
  useEffect(() => {
    let isMounted = true;

    async function fetchUserInfo() {
      try {
        // localStorage와 쿠키 모두에서 토큰 확인
        const localStorageToken = localStorage.getItem('token');
        const cookieToken = document.cookie
          .split('; ')
          .find(row => row.startsWith('token='))
          ?.split('=')[1];
        
        const token = localStorageToken || cookieToken;
        
        if (!token) {
          if (isMounted) {
            router.push('/login');
          }
          return;
        }

        // localStorage에 토큰이 없고 쿠키에만 있으면 localStorage에도 저장 (동기화)
        if (!localStorageToken && cookieToken) {
          localStorage.setItem('token', cookieToken);
        }

        const response = await apiService.getCurrentUser();

        if (response.status === 401) {
          // 토큰이 만료되었거나 유효하지 않은 경우
          localStorage.removeItem('token');
          if (isMounted) {
            router.push('/login');
          }
          return;
        }

        if (response.status !== 200) {
          const errorMessage = response.message || `사용자 정보 조회 실패 (${response.status})`;
          console.error('사용자 정보 조회 실패:', errorMessage);
          if (isMounted) {
            setIsLoading(false);
          }
          return;
        }

        const data = response.data;
        if (isMounted) {
          setUserInfo(data);
          setIsLoading(false);
        }
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '네트워크 오류가 발생했습니다.';
        console.error('사용자 정보 조회 오류:', errorMessage);
        if (isMounted) {
          setIsLoading(false);
        }
      }
    }

    fetchUserInfo();

    return () => {
      isMounted = false;
    };
  }, []);

  // 개발 옵션에서 'changed'로 전환하면 완료 모달 표시
  useEffect(() => {
    setDoneOpen(verificationState === 'changed');
  }, [verificationState]);

  return (
    <main className="flex w-full flex-col">
      <div className="flex h-[100px] items-center px-8">
        <h1 className="text-[24px] font-bold leading-normal text-[#1b2027]">내 정보 수정</h1>
      </div>
      <div className="px-8 pb-20">
        <div className="rounded-lg border border-input-border bg-white p-8">
          <div className="flex flex-col gap-2">
            <label className="w-[100px] text-[15px] font-semibold leading-[1.5] text-text-label">
              아이디 (이메일)
            </label>
            <div className="h-10 rounded-lg border border-input-border bg-neutral-50 px-3 py-2">
              <span className="text-[16px] leading-normal text-neutral-700">
                {isLoading ? '로딩 중...' : (userInfo.email || '이메일 정보 없음')}
              </span>
            </div>
          </div>
          <div className="mt-6 flex flex-col gap-2">
            <label className="w-[100px] text-[15px] font-semibold leading-[1.5] text-text-label">
              비밀번호 변경
            </label>
            <div className="flex items-center gap-3">
              <div className="h-10 flex-1 rounded-lg border border-input-border bg-neutral-50 px-3 py-2">
                <span className="text-[16px] leading-normal text-neutral-700">●●●●●●●●●●</span>
              </div>
              <button
                type="button"
                onClick={() => setOpen(true)}
                className="h-10 rounded-lg bg-bg-gray-light px-4 text-[16px] font-semibold leading-[1.5] text-basic-text"
              >
                비밀번호 변경
              </button>
            </div>
          </div>
        </div>
        <div className="mt-6">
          <button
            type="button"
            onClick={() => setDeleteOpen(true)}
            className="text-[15px] font-medium leading-[1.5] text-[#f64c4c] underline cursor-pointer"
          >
            회원 탈퇴하기
          </button>
        </div>
      </div>

      <ChangePasswordModal
        open={open}
        onClose={() => setOpen(false)}
        onSubmit={() => {
          // TODO: integrate API
        }}
        devVerificationState={
          verificationState === 'changed' ? 'verified' : verificationState
        }
        initialEmail={userInfo.email}
      />

      <MenuAccountOption
        verificationState={verificationState}
        setVerificationState={setVerificationState}
        deleteOpen={deleteOpen}
        setDeleteOpen={setDeleteOpen}
      />

      <PasswordChangeDoneModal
        open={doneOpen}
        onClose={() => setDoneOpen(false)}
      />

      <AccountDeleteModal
        open={deleteOpen}
        onClose={() => setDeleteOpen(false)}
        onConfirm={async () => {
          try {
            await apiService.deleteAccount();

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


