import React from "react";
import { Navigate } from "react-router-dom";
import { OtpLoginForm } from "../components/auth/OtpLoginForm";
import { useAuth } from "../context/AuthContext";

export const LoginPage = () => {
  const { user, isOtpSent, isLoading, authError, requestOtp, verifyOtp } = useAuth();
  const [email, setEmail] = React.useState("");
  const [otp, setOtp] = React.useState("");
  const [error, setError] = React.useState("");

  const displayError = error || authError;

  const handleRequestOtp = async () => {
    const response = await requestOtp({ email });
    if (!response.success) {
      setError(response.error?.message || "Не удалось отправить код");
      return;
    }
    setError("");
  };

  const handleVerifyOtp = async () => {
    const response = await verifyOtp({ email, otp });
    if (!response.success) {
      setError(response.error?.message || "Не удалось подтвердить код");
      return;
    }
    setError("");
  };

  if (user) {
    return <Navigate to="/dashboard" replace />;
  }

  return (
    <div className="flex min-h-screen items-center justify-center px-3 py-6 sm:px-4 sm:py-10">
      <OtpLoginForm
        email={email}
        setEmail={setEmail}
        otp={otp}
        setOtp={setOtp}
        isOtpSent={isOtpSent}
        isLoading={isLoading}
        onRequestOtp={handleRequestOtp}
        onVerifyOtp={handleVerifyOtp}
        error={displayError}
      />
    </div>
  );
};
