import { useState, useContext } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { AuthContext } from "@/contexts/AuthContext";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { motion } from "motion/react";

export function Login() {
  const [isLoading, setIsLoading] = useState(false);
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { login } = useContext(AuthContext);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsLoading(true);

    const formData = new FormData(e.currentTarget);
    const username = formData.get("username") as string;
    const password = formData.get("password") as string;

    try {
      await login(username, password);

      // Login successful, redirect to the requested page or home
      const redirectTo = searchParams.get("redirect") || "/";
      navigate(redirectTo);
    } catch (error) {
      const message = error instanceof Error ? error.message : "Login failed";
      toast.error(message);
      console.error("Login error:", error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <motion.div className="flex min-h-svh flex-row items-center justify-center bg-muted p-6 md:p-10">
      <div className="fixed top-0 w-full backdrop-blur-sm bg-white/40 border-b shadow-sm z-10">
        <div className="mx-auto p-4 sm:p-6">
          <div className="flex items-center gap-2 font-medium text-3xl justify-center sm:justify-start">
            <div className="relative">
              <div className="absolute inset-0 "></div>
              <img 
                src="/cherrybottom.png" 
                alt="Cherry Bottom" 
                className="h-12 w-12 object-contain -rotate-12 transform hover:rotate-0 transition-transform ease-in-out duration-300 relative z-10"
              />
            </div>
            <span className="font-bold font-text-primary">A Cherry On Bottom</span>
          </div>
          <p className="text-sm italic text-muted-foreground text-center sm:text-left ml-32 -mt-1">
            supporting the cherry on top
          </p>
        </div>
      </div>
      <div className="w-full sm:w-[80%] max-w-sm mt-20">
        <LoginForm onSubmit={handleSubmit} isLoading={isLoading} />
      </div>
      
    </motion.div>
  );
}

interface LoginFormProps {
  className?: string;
  isLoading?: boolean;
  onSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
}

function LoginForm({ className, isLoading, onSubmit, ...props }: LoginFormProps) {
  return (
    <motion.div className={cn("flex flex-col gap-6", className)} {...props}>
      <Card className="overflow-hidden rounded-lg shadow-lg">
        <CardHeader className="pb-0">
          <CardTitle className="text-2xl font-bold text-center">Log in to your account</CardTitle>
        </CardHeader>
        <CardContent className="grid p-0 h-full">
          <form className="p-6 md:p-8 flex flex-col gap-6" onSubmit={onSubmit}>
            <div className="grid gap-2">
              <Label htmlFor="username">Username</Label>
              <Input
                id="username"
                name="username"
                type="text"
                required
                disabled={isLoading}
              />
            </div>
            
            <div className="grid gap-2">
              <Label htmlFor="password">Password</Label>
              <Input 
                id="password" 
                name="password" 
                type="password" 
                required 
                disabled={isLoading}
              />
            </div>
            
            <Button type="submit" className="w-full" disabled={isLoading}>
              {isLoading ? "Logging in..." : "Log In"}
            </Button>
          </form>
        
        </CardContent>
      </Card>
    </motion.div>
  );
}
