import { FormEvent, useContext, useEffect, useState } from 'react';
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { EyeIcon, EyeOffIcon, Loader } from 'lucide-react';
import Link from 'next/link';
import { routes } from '@/lib/routes';
import { useToast } from '@/hooks/use-toast';
import { AuthContext } from '@/helpers/context/AuthProvider';
import { setEduConnectAccessToken } from '@/helpers/token.helper';
import { useRouter } from 'next/navigation';

export default function LoginForm() {
  const router = useRouter()
  const [showPassword, setShowPassword] = useState(false);
  const [loading ,setLoading] = useState<boolean>(false)
  const [inputValues , setInputValues] = useState<Record<string,any>>({});
  const [error , setError] = useState<Record<string,any>>({});


  const { fetchUser , user } = useContext(AuthContext);
  const { toast } = useToast()

  const handleFormSubmit = async (e : FormEvent<HTMLFormElement>) :Promise<void> => {
    e.preventDefault();

    setLoading(false)
    const formData = new FormData(e.currentTarget)
    Object.entries(inputValues).forEach(([key, value]) => {
      formData.append(key, value);
    });

    try{
      const res = await fetch(`${process.env.NEXT_PUBLIC_EDU_CONNECT_HOST}/api/session/create` , {
        method : 'POST' , 
        body : formData
      })
      
      const data : any = await res.json();

      if(res.status == 200){
        toast({
          title : 'Sucessfully logged in !',
          description : `${data?.message}`,
          variant : 'success'
        })

        setInputValues({})
        await fetchUser(data?.session_key)
        setEduConnectAccessToken(data?.session_key)
        router.push(routes.INDEX_PAGE)
      }else{
        setError(data?.error)
        toast({
          title : 'Error logging in !',
          description : `${data?.message}`,
          variant : 'destructive'
        })
      }
    }catch(e : any){
      toast({
        title : 'Error logging in !',
        description : `${error?.message}`,
        variant : 'destructive'
      })
    }finally{
      setLoading(false)
    }

  }

  useEffect(() => {
    setError({})
    setInputValues({})
  },[])

  useEffect(() => {
    if(user){
      router.push(routes.INDEX_PAGE)
    }
  },[router])

  return (
    <div className="flex items-center justify-center min-h-[60vh]">
      <Card className="w-full max-w-md  border border-purple-700/20 shadow shadow-purple-700/40">
        <CardHeader className="space-y-3">
          <CardTitle className="text-2xl font-bold text-purple-600">Login</CardTitle>
          <CardDescription className="text-gray-600">
            Enter your email and password to login to your account
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form className="space-y-6" onSubmit={handleFormSubmit}>
            <div className="space-y-2">
              <Label htmlFor="email" className="text-gray-700">Email</Label>
              <Input 
                id="email" 
                type="email" 
                placeholder="Enter your email"
                className="h-11 px-4 bg-gray-50/50 border-gray-200 focus:border-purple-500 focus:ring-purple-500"
                onChange={(e) => setInputValues((prev : any) => ({...prev , email : e.target.value}))}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="password" className="text-gray-700">Password</Label>
              <div className="relative">
                <Input 
                  id="password" 
                  type={"password"}
                  placeholder="Enter your password"
                  className="h-11 px-4 bg-gray-50/50 border-gray-200 focus:border-purple-500 focus:ring-purple-500 pr-10"
                  onChange={(e) => setInputValues((prev : any) => ({...prev , password : e.target.value}))}
                  
                />
              </div>
            </div>
            
            <div className="flex items-center justify-between text-sm">
              <label className="flex items-center space-x-2 text-gray-600">
                <input type="checkbox" className="rounded border-gray-300 text-purple-600 focus:ring-purple-500" />
                <span>Remember me</span>
              </label>
            </div>

            <Button 
              type="submit" 
              className="w-full h-11 bg-purple-600 hover:bg-purple-700 text-white font-semibold"
            >
              {
                loading ? 
                <>
                  <Loader />
                  Login
                </>
                : 'Login'
              }
            </Button>

            <div className="text-center text-sm text-gray-600">
              Don't have an account?{' '}
              <Link href={routes.LOGIN_ROUTES} className="text-purple-600 hover:text-purple-700 font-semibold">
                Register
              </Link>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}