import { zodResolver } from '@hookform/resolvers/zod';
import { useSetAtom } from 'jotai';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { useRevalidator } from 'react-router';
import { toast } from 'sonner';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { authClient, tokenAtom } from '@/lib/auth/client';
import { cn } from '@/lib/utils';

const loginFormSchema = z.object({
  username: z.string(),
  password: z.string(),
});

export default function Login({
  className,
  ...props
}: React.ComponentProps<'div'>) {
  const [loading, setLoading] = useState(false);
  const form = useForm<z.infer<typeof loginFormSchema>>({
    resolver: zodResolver(loginFormSchema),
    defaultValues: {
      username: '',
      password: '',
    },
  });

  const { revalidate } = useRevalidator();
  const setToken = useSetAtom(tokenAtom);

  function onSubmit(values: z.infer<typeof loginFormSchema>) {
    setLoading(true);
    const { username, password } = values;
    authClient.token.actions
      .generateToken({
        username,
        password,
        allowRefresh: true,
        audience: 'spvtms',
      })
      .then(([error, data]) => {
        if (error) {
          return toast.error(
            (error.error as unknown as Error).message ?? 'Invalid credentials',
          );
        }
        setToken(data.token);
        setTimeout(() => {
          revalidate();
        }, 1000);
      })
      .finally(() => {
        setLoading(false);
      });
  }

  return (
    <div className="bg-muted flex flex-col items-center justify-center p-6 min-h-svh md:p-10">
      <div className="max-w-sm w-full md:max-w-3xl">
        <div className={cn('flex flex-col gap-6', className)} {...props}>
          <Card className="overflow-hidden">
            <CardContent className="grid p-0 md:grid-cols-2">
              <Form {...form}>
                <form
                  className="p-6 md:p-8"
                  onSubmit={form.handleSubmit(onSubmit)}
                >
                  <div className="flex flex-col gap-6">
                    <div className="flex flex-col items-center text-center">
                      <div className="bg-foreground [mask-image:url(/csmon_logo.svg)] [mask-size:100%_100%] h-20 w-40" />

                      <p className="text-muted-foreground text-balance">
                        Login to your {import.meta.env.VITE_APP_NAME} account
                      </p>
                    </div>
                    <FormField
                      control={form.control}
                      name="username"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Username</FormLabel>
                          <FormControl>
                            <Input
                              placeholder={
                                import.meta.env.VITE_EMAIL_PLACEHOLDER
                              }
                              {...field}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="password"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Password</FormLabel>
                          <FormControl>
                            <Input
                              type="password"
                              placeholder="*********"
                              {...field}
                            />
                          </FormControl>
                          <FormDescription>
                            <a
                              href="#"
                              className="ml-auto text-sm underline-offset-2 hover:underline"
                            >
                              Forgot your password?
                            </a>
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <Button type="submit" className="w-full">
                      Login
                    </Button>
                  </div>
                </form>
              </Form>
              {/* <div className="bg-muted relative hidden md:block"> */}
              {/* <img
                  src="/login.jpg"
                  alt="Construction Site"
                  className="absolute inset-0 h-full w-full object-cover brightness-110 saturate-110"
                /> */}
              {/* </div> */}
            </CardContent>
            {loading ? (
              <div className="absolute inset-0 filter-blur-lg filter" />
            ) : null}
          </Card>
          <div className="text-muted-foreground hover:[&_a]:text-primary text-center text-balance text-xs [&_a]:underline [&_a]:underline-offset-4">
            By clicking continue, you agree to our{' '}
            <a href="#">Terms of Service</a> and <a href="#">Privacy Policy</a>.
          </div>
        </div>
      </div>
    </div>
  );
}
