
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "@/contexts/auth";
import { useToast } from "@/hooks/useToast.wrapper";
import { verifyServerConnection } from "@/contexts/auth/auth.utils";

// 분리된 컴포넌트들 임포트
import RegisterHeader from "@/components/auth/RegisterHeader";
import RegisterForm from "@/components/auth/RegisterForm";
import LoginLink from "@/components/auth/LoginLink";
import ServerStatusAlert from "@/components/auth/ServerStatusAlert";
import TestConnectionSection from "@/components/auth/TestConnectionSection";
import SupabaseConnectionStatus from "@/components/auth/SupabaseConnectionStatus";
import RegisterErrorDisplay from "@/components/auth/RegisterErrorDisplay";

const Register = () => {
  const [registerError, setRegisterError] = useState<string | null>(null);
  const [testResults, setTestResults] = useState<any>(null);
  const [serverStatus, setServerStatus] = useState<{
    checked: boolean;
    connected: boolean;
    message: string;
  }>({
    checked: false,
    connected: false,
    message: "서버 연결 상태를 확인 중입니다..."
  });
  
  const { toast } = useToast();
  const navigate = useNavigate();
  const { signUp, user } = useAuth();
  
  // 이미 로그인된 경우 메인 페이지로 리다이렉트
  useEffect(() => {
    if (user) {
      navigate("/");
    }
  }, [user, navigate]);

  // 서버 연결 상태 확인
  useEffect(() => {
    checkServerConnection();
  }, []);

  // 서버 연결 상태 확인 함수
  const checkServerConnection = async () => {
    try {
      const status = await verifyServerConnection();
      setServerStatus({
        checked: true,
        connected: status.connected,
        message: status.message
      });
      
      // 연결 실패 시 토스트 표시
      if (!status.connected) {
        toast({
          title: "서버 연결 문제",
          description: status.message,
          variant: "destructive"
        });
      }
    } catch (error: any) {
      setServerStatus({
        checked: true,
        connected: false,
        message: `연결 확인 중 오류: ${error.message || '알 수 없는 오류'}`
      });
    }
  };

  return (
    <div className="min-h-screen flex flex-col items-center justify-center p-6 bg-neuro-background">
      <div className="w-full max-w-md">
        <RegisterHeader />
        
        <ServerStatusAlert 
          serverStatus={serverStatus} 
          checkServerConnection={checkServerConnection} 
        />
        
        <RegisterErrorDisplay error={registerError} />
        
        <RegisterForm
          signUp={signUp}
          serverStatus={serverStatus}
          setServerStatus={setServerStatus}
          setRegisterError={setRegisterError}
        />
        
        <LoginLink />
        
        <TestConnectionSection
          setLoginError={setRegisterError}
          setTestResults={setTestResults}
        />
        
        <SupabaseConnectionStatus testResults={testResults} />
      </div>
    </div>
  );
};

export default Register;
