import { useKeyring } from "../hooks"
import { Layout2 } from "@/components/Layout2"

import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import {
    Card,
    CardContent,
    CardHeader,
    CardTitle,
    CardDescription,
    CardFooter,
} from "@/components/ui/card"
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
} from "@/components/ui/form"
import { EyeIcon, EyeOffIcon, LayersIcon } from "lucide-react"
import { useForm, SubmitHandler } from "react-hook-form"
import { useState } from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { cn } from "@/lib/utils"
import { Link } from "react-router-dom"

import { Logo } from "../../../components"

const FormSchema = z.object({
    password: z.string({ required_error: "You must specify a password" }),
})

export const UnlockKeyring = () => {
    const { unlock } = useKeyring()
    const [showPassword, setShowPassword] = useState<boolean>(false)

    const form = useForm<z.infer<typeof FormSchema>>({
        resolver: zodResolver(FormSchema),
    })

    const {
        control,
        handleSubmit,
        reset,
        getValues,
        setError,
        formState: { errors, isSubmitting, isSubmitSuccessful },
    } = form

    const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = async ({ password }) => {
        try {
            await unlock(password)
        } catch (e) {
            setError("password", { message: "Incorrect password provided" })
        }
    }

    const togglePasswordVisibility = () => {
        setShowPassword((prev) => !prev)
    }

    return (
        <Layout2>
            <Form {...form}>
                <form className="relative grow" onSubmit={handleSubmit(onSubmit)}>
                    <Card className="absolute flex flex-col flex-grow w-full max-w-md min-h-full shadow-none">
                        <CardHeader className="text-center">
                            <CardTitle className="mt-6 mb-6 py-[5px] px-[30px] text-2xl leading-4">
                                <Logo cName="fill-primary" />
                            </CardTitle>
                            <CardDescription className="mt-2 text-sm">
                                Unfortunately, we are unable to assist you in restoring your password.
                                The only recommendation we can offer is to reinstall the extension;
                                however, please note that this will result in the loss of all account data.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="relative content-center flex flex-grow">
                            <FormField
                                control={control}
                                name="password"
                                render={({ field, fieldState }) => (
                                    <FormItem className="grid w-full max-w-sm items-center gap-1.5 my-4">
                                        <div className="relative">
                                            <FormControl>
                                                <Input
                                                    id="password"
                                                    type={showPassword ? "text" : "password"}
                                                    disabled={isSubmitting}
                                                    placeholder="Enter your password"
                                                    {...field}
                                                />
                                            </FormControl>
                                            <button
                                                onClick={handleSubmit(togglePasswordVisibility)}
                                                className="absolute -translate-y-1/2 top-1/2 -translate-x-1/2 right-2"
                                            >
                                                {showPassword ? (
                                                    <EyeOffIcon className="w-5 h-5" />
                                                ) : (
                                                    <EyeIcon className="w-5 h-5" />
                                                )}
                                            </button>
                                        </div>
                                        {fieldState.invalid && fieldState.error?.message && (
                                            <span className="absolute top-1/2 pt-4 text-xs text-red-500">
                                                {fieldState.error?.message}
                                            </span>
                                        )}
                                    </FormItem>
                                )}
                            />
                        </CardContent>
                        <CardFooter className="flex flex-col space-y-4 justify-end">
                            <Button disabled={isSubmitting} type="submit" size="full" className={cn("text-lg py-3")}>
                                Unlock Wallet
                            </Button>
                            <Link
                                data-testid="btnGoToOptions"
                                to="/options"
                                target="_blank"
                                rel="noopener noreferrer"
                                className="w-full"
                            >
                                <Button
                                    type="button"
                                    disabled={isSubmitting}
                                    variant="secondary"
                                    size="full"
                                    className={cn("text-lg py-3")}
                                >
                                    Options
                                </Button>
                            </Link>
                        </CardFooter>
                    </Card>
                </form>
            </Form>
        </Layout2>
    )
}
