"use client"

import React from 'react'
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import {
    Card,
    CardContent,
} from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Button } from '@/components/ui/button'
import { login } from '@/actions/auth'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { EyeIcon, EyeOffIcon, Loader2Icon } from 'lucide-react'

const formSchema = z.object({
    email: z.string({message: "Please use a valid email address"}).email(),
    password: z.string().min(1, 'Please enter a valid password'),
})

const LoginForm = () => {
    const router = useRouter();
    const [password , setPassword] = React.useState(false)
    const [loading, setLoading] = React.useState(false)
    const [error, setError] = React.useState("")
    const [showPass, setShowPass] = React.useState(false)

    const form = useForm<z.infer<typeof formSchema>>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            email: "",
            password: "",
        },
    })
    
    const onSubmit = async (values: z.infer<typeof formSchema>) => {
        setError("")
        setLoading(true)
        const response = await login(values.email, values.password)
        if (response && !response?.success) {
            setError(response.message);
            setLoading(false);
            return;
        }
        router.push("/")
    }
    return (
        <Card className="overflow-hidden">
            <CardContent className="grid p-02">
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="p-6 md:p-8">
                        <div className="flex flex-col gap-6">
                            <div className="flex flex-col items-center text-center">
                                <h1 className="text-2xl font-bold">Welcome back</h1>
                                <p className="text-balance text-muted-foreground">
                                    Login to Admin Panel
                                </p>
                            </div>
                            <div className="grid gap-2">
                                <FormField
                                    control={form.control}
                                    name="email"
                                    render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Email</FormLabel>
                                        <FormControl>
                                        <Input type="email" placeholder="me@example.com" {...field} disabled={loading}/>
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                    )}
                                />
                            </div>
                            <div className="grid gap-2">
                                <FormField
                                    control={form.control}
                                    name="password"
                                    render={({ field }) => (
                                    <FormItem>
                                        <div className="flex items-center">
                                            <FormLabel>Password</FormLabel>
                                            <Link
                                                href="/forgot-password"
                                                className="ml-auto text-sm underline-offset-2 hover:underline"
                                            >
                                                Forgot your password?
                                            </Link>
                                        </div>
                                            <div className="relative">
                                            <FormControl>
                                                <Input type={showPass ? "text": "password"} placeholder="*******" className="pr-8" {...field} disabled={loading}/>
                                            </FormControl>
                                            <div className="absolute top-0.5 right-0.5 z-40">
                                                <Button type="button" variant="ghost" size="sm" disabled={loading} onClick={() => setShowPass(!showPass)}>
                                                {showPass ? <EyeIcon /> : <EyeOffIcon />}
                                                </Button>
                                            </div>
                                        </div>
                                        <FormMessage />
                                    </FormItem>
                                    )}
                                />
                            </div>
                            <Button type="submit" variant="black" className="w-full">
                                {loading && (<Loader2Icon className="animate-spin"/>)}
                                <span>Login</span>
                            </Button>                    
                        </div>
                        {error && error !== "" && (
                            <div className="border rounded-lg bg-gundam-red/90 opacity-80 py-1.5 px-6 mt-2">
                                <p className="text-white font-bold">{error}</p>
                            </div>
                        )}
                    </form>
                </Form>
            </CardContent>
        </Card>
    )
}

export default LoginForm