import { createLazyFileRoute, useNavigate } from "@tanstack/react-router";
import { useMutation } from "@tanstack/react-query";
import { Input } from '@/shadcn/components/ui/input.tsx';
import { Button } from '@/shadcn/components/ui/button.tsx';
import { Alert } from '@/shadcn/components/ui/alert.tsx';
import { Card } from '@/shadcn/components/ui/card.tsx';
import { 
	Form, 
	FormControl, 
	FormField, 
	FormItem, 
	FormLabel, 
	FormMessage 
} from '@/shadcn/components/ui/form.tsx';
import client from "../../honoClient";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect, useState } from "react";
import useAuth from "@/hooks/useAuth";
import { TbArrowNarrowRight } from "react-icons/tb";
import logo from "@/assets/logos/amati-logo.png";

export const Route = createLazyFileRoute("/login/")({
	component: LoginPage,
});

type FormSchema = {
	username: string;
	password: string;
};

const formSchema = z.object({
	username: z.string().min(1, "Kolom ini wajib diisi"),
	password: z.string().min(1, "Kolom ini wajib diisi"),
});

export default function LoginPage() {
	const [errorMessage, setErrorMessage] = useState("");
	const navigate = useNavigate();

	const { isAuthenticated, saveAuthData } = useAuth();

	const form = useForm<FormSchema>({
		resolver: zodResolver(formSchema),
		defaultValues: {
			username: "",
			password: "",
		},
	});

	useEffect(() => {
		if (isAuthenticated) {
			navigate({
				to: "/dashboard",
				replace: true,
			});
		}
	}, [navigate, isAuthenticated]);

	const loginMutation = useMutation({
		mutationFn: async (values: FormSchema) => {
			const res = await client.auth.login.$post({
				form: values,
			});

			if (res.ok) {
				return await res.json();
			}

			throw res;
		},

		onSuccess: (data) => {
			saveAuthData(
				{
					id: data.user.id,
					name: data.user.name,
					permissions: data.user.permissions,
				},
				data.accessToken
			);
		},

		onError: async (error) => {
			console.log("error!");
			if (error instanceof Response) {
				const body = await error.json();
				setErrorMessage(body.message as string);
				return;
			}
			console.log("bukan error");
		},
	});

	const handleSubmit = (values: FormSchema) => {
		loginMutation.mutate(values);
	};

	return (
		<div className="flex flex-col w-screen h-screen 3xl:max-w-screen-2xl 3xl:mx-auto 3xl:px-4 overflow-hidden">
			{/* Navbar */}
			<nav className="flex w-full bg-transparent px-8 py-7 justify-between">
				<div className="flex">
					<img src="../src/assets/logos/amati-logo.png" alt="Amati Logo" className="h-4 object-contain" />
				</div>
			</nav>

			{/* Background shapes */}
			<div className="absolute inset-0 flex -z-20 overflow-hidden">
				<div className="relative h-[50vw] lg:h-screen z-0">
					<div className="-translate-y-[calc(40vw+2rem)] lg:translate-y-0 w-full lg:-translate-x-[calc(10vh-60vw)]">
						<span className="absolute scale-50 lg:scale-50 -rotate-12 w-[100vw] h-[100vw] lg:w-[100vh] lg:h-[100vh] border border-gray-800 flex rounded-3xl"></span>
						<span className="absolute scale-[85%] lg:scale-[70%] -rotate-12 w-[100vw] h-[100vw] lg:w-[100vh] lg:h-[100vh] border border-gray-400 flex rounded-3xl"></span>
						<span className="absolute scale-[120%] lg:scale-90 -rotate-12 w-[100vw] h-[100vw] lg:w-[100vh] lg:h-[100vh] border border-gray-300 flex rounded-3xl"></span>
						<span className="absolute scale-150 lg:scale-110 -rotate-12 w-[100vw] h-[100vw] lg:w-[100vh] lg:h-[100vh] border border-gray-200 hidden lg:flex rounded-3xl"></span>
					</div>
				</div>
			</div>

			{/* Sign In form */}
			<div className="flex w-full min-h-screen ml-0 lg:ml-28 3xl:ml-40 -mt-16 justify-center lg:justify-start items-center"> 
				<Card className="w-full sm:w-3/5 lg:w-2/6 px-8 sm:p-0 h-auto bg-transparent border-none shadow-none">
				<h1 className="mb-2 text-4xl font-bold leading-10 tracking-tighter">Sign In</h1>
				<p className="text-sm mb-10 leading-4 text-muted-foreground">
					Baru mengenal aplikasi ini?{' '}
					<a href="/register" className="text-blue-600 font-bold hover:text-blue-800">
					Daftar sekarang
					</a>
				</p>
				<Form {...form}>
					<form onSubmit={form.handleSubmit(handleSubmit)}>
					<div className="space-y-5">
						{errorMessage && (
						<Alert variant="destructive">
							<p>{errorMessage}</p>
						</Alert>
						)}
						<FormField
						name="username"
						render={({ field }) => (
							<FormItem className="text-sm">
							<FormLabel className="font-semibold leading-4">Email/Username</FormLabel>
							<FormControl>
								<Input
								placeholder="eg; user@mail.com"
								disabled={loginMutation.isPending}
								className={form.formState.errors.username ? "border-red-500" : ""}
								{...field}
								/>
							</FormControl>
							<FormMessage />
							</FormItem>
						)}
						/>
						<FormField
						name="password"
						render={({ field }) => (
							<FormItem className="text-sm">
							<FormLabel className="font-semibold leading-4">Kata sandi</FormLabel>
							<FormControl>
								<Input
								type="password"
								placeholder="*****"
								disabled={loginMutation.isPending}
								className={form.formState.errors.password ? "border-red-500" : ""}
								{...field}
								/>
							</FormControl>
							<FormMessage />
							</FormItem>
						)}
						/>
						<p className="text-sm">
						<a href="/forgot-password" className="text-blue-600 font-bold hover:text-blue-800 leading-4">
							Lupa kata sandi?
						</a>
						</p>
					</div>
					<div className="flex mt-10">
						<Button
						type="submit"
						disabled={loginMutation.isPending}
						variant="default"
						className="flex w-full justify-between bg-blue-600 text-white hover:bg-blue-700"
						>
						<span className="leading-5">Sign In</span>
						<TbArrowNarrowRight className="h-5 w-5" />
						</Button>
					</div>
					</form>
				</Form>
				</Card>
			</div>
		</div>
	);
}