import type { Route } from "./+types/login";
import { LoginForm } from "~/components/auth/login-form";
import { PublicRoute } from "~/components/auth/protected-route";
import { useAuth } from "~/contexts/auth-context";
import { useEffect, useState } from "react";
import { useNavigate, useSearchParams } from "react-router";
import { LoadingPage } from "~/components/ui/loading";

export function meta({}: Route.MetaArgs) {
  return [
    { title: "ورود - سیستم مدیریت فناوری و نوآوری" },
    {
      name: "description",
      content: "ورود به سیستم مدیریت فناوری و نوآوری اینوژن",
    },
    { name: "keywords", content: "ورود, سیستم مدیریت, فناوری, نوآوری, اینوژن" },
    { name: "robots", content: "noindex, nofollow" },
  ];
}

export default function Login() {
  const { isAuthenticated, isLoading } = useAuth();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const returnTo = searchParams.get("returnTo");
  const [isRedirecting, setIsRedirecting] = useState(false);

  useEffect(() => {
    if (isAuthenticated && !isLoading && !isRedirecting) {
      setIsRedirecting(true);

      // Small delay to prevent flash
      setTimeout(() => {
        const redirectPath =
          returnTo && returnTo !== "/login" ? returnTo : "/dashboard";
        navigate(redirectPath, { replace: true });
      }, 100);
    }
  }, [isAuthenticated, isLoading, navigate, returnTo, isRedirecting]);

  const handleLoginSuccess = () => {
    if (!isRedirecting) {
      setIsRedirecting(true);

      const redirectPath =
        returnTo && returnTo !== "/login" ? returnTo : "/dashboard";

      // Immediate redirect on successful login
      navigate(redirectPath, { replace: true });
    }
  };

  // Show loading state during redirect
  if (isAuthenticated && (isLoading || isRedirecting)) {
    return (
      <div
        className="min-h-screen flex items-center justify-center"
        style={{
          background:
            "linear-gradient(135deg, var(--color-login-dark-start) 0%, var(--color-login-dark-end) 100%)",
        }}
      >
        <div className="text-center space-y-6 max-w-md mx-auto p-8">
          <div className="flex justify-center">
            <div className="w-8 h-8 border-2 border-[var(--color-login-primary)] border-t-transparent rounded-full animate-spin"></div>
          </div>
          <div className="space-y-2">
            <h2 className="text-lg font-medium font-persian text-white">
              در حال انتقال...
            </h2>
            <p className="text-sm font-persian leading-relaxed text-gray-300">
              در حال هدایت به صفحه مقصد
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <PublicRoute>
      <LoginForm onSuccess={handleLoginSuccess} />
    </PublicRoute>
  );
}
