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

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

  React.useEffect(() => {
    if (isDemoMode) {
      setEmail(DEMO_LOGIN_EMAIL);
    }
  }, [isDemoMode]);

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

  const displayError = error || authError;

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

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

  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}
        roleHint={roleHint}
        setRoleHint={setRoleHint}
        otp={otp}
        setOtp={setOtp}
        isOtpSent={isOtpSent}
        isLoading={isLoading}
        isDemoMode={isDemoMode}
        onRequestOtp={handleRequestOtp}
        onVerifyOtp={handleVerifyOtp}
        error={displayError}
      />
    </div>
  );
};
