
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { ArrowRight, Mail, KeyRound, User, Eye, EyeOff } from "lucide-react";
import { useToast } from "@/hooks/useToast.wrapper";
import { verifyServerConnection } from "@/contexts/auth/auth.utils";

interface RegisterFormProps {
  signUp: (email: string, password: string) => Promise<{
    error: any;
    user: any;
  }>;
  serverStatus: {
    checked: boolean;
    connected: boolean;
    message: string;
  };
  setServerStatus: React.Dispatch<
    React.SetStateAction<{
      checked: boolean;
      connected: boolean;
      message: string;
    }>
  >;
  setRegisterError: React.Dispatch<React.SetStateAction<string | null>>;
}

const RegisterForm: React.FC<RegisterFormProps> = ({
  signUp,
  serverStatus,
  setServerStatus,
  setRegisterError,
}) => {
  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  
  const { toast } = useToast();
  const navigate = useNavigate();

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    setRegisterError(null);
    
    // 서버 연결 상태 재확인
    if (!serverStatus.connected) {
      const currentStatus = await verifyServerConnection();
      setServerStatus({
        checked: true,
        connected: currentStatus.connected,
        message: currentStatus.message
      });
      
      if (!currentStatus.connected) {
        toast({
          title: "서버 연결 실패",
          description: "서버에 연결할 수 없습니다. 네트워크 또는 서버 상태를 확인하세요.",
          variant: "destructive"
        });
        return;
      }
    }
    
    if (!username || !email || !password || !confirmPassword) {
      toast({
        title: "입력 오류",
        description: "모든 필드를 입력해주세요.",
        variant: "destructive",
      });
      return;
    }
    
    if (password !== confirmPassword) {
      toast({
        title: "비밀번호 불일치",
        description: "비밀번호와 비밀번호 확인이 일치하지 않습니다.",
        variant: "destructive",
      });
      return;
    }
    
    setIsLoading(true);
    
    try {
      const { error, user } = await signUp(email, password);
      
      if (error) {
        setRegisterError(error.message || '알 수 없는 오류가 발생했습니다.');
      } else if (user) {
        // 회원가입 성공 시 로그인 페이지로 이동
        navigate("/login");
      }
    } catch (error: any) {
      console.error("회원가입 처리 중 예외 발생:", error);
      setRegisterError(error.message || '예상치 못한 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="neuro-flat p-8 mb-6">
      <form onSubmit={handleRegister}>
        <div className="space-y-6">
          <div className="space-y-2">
            <Label htmlFor="username" className="text-base">이름</Label>
            <div className="relative">
              <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 h-5 w-5" />
              <Input
                id="username"
                type="text"
                placeholder="홍길동"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                className="pl-10 neuro-pressed"
              />
            </div>
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="email" className="text-base">이메일</Label>
            <div className="relative">
              <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 h-5 w-5" />
              <Input
                id="email"
                type="email"
                placeholder="your@email.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="pl-10 neuro-pressed"
              />
            </div>
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="password" className="text-base">비밀번호</Label>
            <div className="relative">
              <KeyRound className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 h-5 w-5" />
              <Input
                id="password"
                type={showPassword ? "text" : "password"}
                placeholder="••••••••"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="pl-10 neuro-pressed"
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500"
              >
                {showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
              </button>
            </div>
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="confirmPassword" className="text-base">비밀번호 확인</Label>
            <div className="relative">
              <KeyRound className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 h-5 w-5" />
              <Input
                id="confirmPassword"
                type={showPassword ? "text" : "password"}
                placeholder="••••••••"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                className="pl-10 neuro-pressed"
              />
            </div>
          </div>
          
          <Button
            type="submit"
            className="w-full bg-neuro-income hover:bg-neuro-income/80 text-white py-6 h-auto"
            disabled={isLoading || (!serverStatus.connected && serverStatus.checked)}
          >
            {isLoading ? "가입 중..." : "회원가입"} {!isLoading && <ArrowRight className="ml-2 h-5 w-5" />}
          </Button>
        </div>
      </form>
    </div>
  );
};

export default RegisterForm;
