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, verifySupabaseConnection } from "@/utils/auth/networkUtils";

// 분리된 컴포넌트들 임포트
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";
import { ServerConnectionStatus } from "@/components/auth/types";

const Register = () => {
  const [registerError, setRegisterError] = useState<string | null>(null);
  const [testResults, setTestResults] = useState<any>(null);
  const [serverStatus, setServerStatus] = useState<ServerConnectionStatus>({
    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 basicStatus = await verifyServerConnection();
      
      // 기본 확인에 실패하면 강화된 확인 시도
      if (!basicStatus.connected) {
        const enhancedStatus = await verifySupabaseConnection();
        
        setServerStatus({
          checked: true,
          connected: enhancedStatus.connected,
          message: enhancedStatus.message + (enhancedStatus.details ? ` (${enhancedStatus.details})` : '')
        });
        
        if (!enhancedStatus.connected) {
          toast({
            title: "서버 연결 문제",
            description: enhancedStatus.message,
            variant: "destructive"
          });
        }
      } else {
        // 기본 확인에 성공한 경우
        setServerStatus({
          checked: true,
          connected: true,
          message: basicStatus.message
        });
      }
    } catch (error: any) {
      setServerStatus({
        checked: true,
        connected: false,
        message: `연결 확인 중 오류: ${error.message || '알 수 없는 오류'}`
      });
      
      toast({
        title: "연결 확인 오류",
        description: error.message || '알 수 없는 오류',
        variant: "destructive"
      });
    }
  };

  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;
