'use client';

import { Separator } from '@/components/ui/separator';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@/components/ui/form';
import { useState, useTransition } from 'react';

import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { useForm } from 'react-hook-form';
import { Loader2, Eye, EyeOff } from 'lucide-react';
import { client } from '@/lib/auth/auth-client';
import { toast } from 'sonner';
import { useRouter } from 'next/navigation';

function useSecuritySchema() {
  return z
    .object({
      currentPassword: z
        .string()
        .min(6, { message: 'Adgangskoden skal være mindst 6 tegn lang' }),
      password: z
        .string()
        .min(6, { message: 'Adgangskoden skal være mindst 6 tegn lang' }),
      passwordConfirmation: z
        .string()
        .min(6, { message: 'Adgangskoden skal være mindst 6 tegn lang' })
    })
    .refine((data) => data.password === data.passwordConfirmation, {
      message: 'Adgangskoderne stemmer ikke overens',
      path: ['passwordConfirmation']
    });
}

type SecurityFormData = z.infer<ReturnType<typeof useSecuritySchema>>;

export default function SecurityForm() {
  const [loading, startTransition] = useTransition();
  const router = useRouter();
  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showPasswordConfirmation, setShowPasswordConfirmation] =
    useState(false);
  const schema = useSecuritySchema();

  const form = useForm<SecurityFormData>({
    resolver: zodResolver(schema),
    defaultValues: {
      currentPassword: '',
      password: '',
      passwordConfirmation: ''
    }
  });

  const onSubmit = (data: SecurityFormData) => {
    startTransition(async () => {
      try {
        await client.changePassword({
          currentPassword: data.currentPassword,
          newPassword: data.password,
          fetchOptions: {
            onSuccess: () => {
              toast.success('Adgangskode opdateret succesfuldt');
              form.reset();
              router.refresh();
            },
            onError: (error) => {
              toast.error(
                error.error.message ||
                  'Der opstod en fejl ved opdatering af adgangskoden'
              );
            }
          }
        });
      } catch {
        toast.error('Der opstod en fejl ved opdatering af adgangskoden');
      }
    });
  };
  return (
    <Card className='w-full gap-3 rounded-none border-0 bg-neutral-100 px-5 pt-4 pb-7 font-serif shadow-none'>
      <CardHeader className='p-0'>
        <CardTitle className='text-client-dark text-2xl'>Sikkerhed</CardTitle>
        <Separator />
      </CardHeader>
      <CardContent className='p-0'>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className='grid gap-3.5'>
            <FormField
              control={form.control}
              name='currentPassword'
              render={({ field }) => (
                <FormItem className='gap-1'>
                  <FormLabel className='text-base'>
                    Nuværende adgangskode
                  </FormLabel>
                  <div className='relative'>
                    <FormControl>
                      <Input
                        className='border-border h-11 rounded-none bg-white px-4 pr-12 pl-2.5 text-neutral-700 shadow-none'
                        id='currentPassword'
                        type={showCurrentPassword ? 'text' : 'password'}
                        autoComplete='current-password'
                        {...field}
                      />
                    </FormControl>
                    <Button
                      type='button'
                      variant='ghost'
                      size='icon'
                      className='absolute top-1/2 right-2 -translate-y-1/2 cursor-pointer hover:bg-transparent'
                      onClick={() =>
                        setShowCurrentPassword(!showCurrentPassword)
                      }
                    >
                      {showCurrentPassword ? (
                        <EyeOff className='size-6 text-neutral-700' />
                      ) : (
                        <Eye className='size-6 text-neutral-700' />
                      )}
                    </Button>
                  </div>

                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name='password'
              render={({ field }) => (
                <FormItem className='gap-1'>
                  <FormLabel className='text-base'>Ny adgangskode</FormLabel>
                  <div className='relative'>
                    <FormControl>
                      <Input
                        className='border-border h-11 rounded-none bg-white px-4 pr-12 pl-2.5 text-neutral-700 shadow-none'
                        id='password'
                        type={showPassword ? 'text' : 'password'}
                        autoComplete='new-password'
                        {...field}
                      />
                    </FormControl>
                    <Button
                      type='button'
                      variant='ghost'
                      size='icon'
                      className='absolute top-1/2 right-2 -translate-y-1/2 cursor-pointer hover:bg-transparent'
                      onClick={() => setShowPassword(!showPassword)}
                    >
                      {showPassword ? (
                        <EyeOff className='size-6 text-neutral-700' />
                      ) : (
                        <Eye className='size-6 text-neutral-700' />
                      )}
                    </Button>
                  </div>

                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name='passwordConfirmation'
              render={({ field }) => (
                <FormItem className='gap-1'>
                  <FormLabel className='text-base'>
                    Gentag adgangskode
                  </FormLabel>
                  <div className='relative'>
                    <FormControl>
                      <Input
                        className='border-border h-11 rounded-none bg-white px-4 pr-12 pl-2.5 text-neutral-700 shadow-none'
                        id='passwordConfirmation'
                        type={showPasswordConfirmation ? 'text' : 'password'}
                        autoComplete='new-password'
                        {...field}
                      />
                    </FormControl>
                    <Button
                      type='button'
                      variant='ghost'
                      size='icon'
                      className='absolute top-1/2 right-2 -translate-y-1/2 cursor-pointer hover:bg-transparent'
                      onClick={() =>
                        setShowPasswordConfirmation(!showPasswordConfirmation)
                      }
                    >
                      {showPasswordConfirmation ? (
                        <EyeOff className='size-6 text-neutral-700' />
                      ) : (
                        <Eye className='size-6 text-neutral-700' />
                      )}
                    </Button>
                  </div>

                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Submit */}
            <Button
              type='submit'
              className='h-11 min-w-42 justify-self-end bg-neutral-900 font-sans text-base md:mt-22'
              disabled={loading}
            >
              {loading ? <Loader2 className='animate-spin' /> : 'gem ændringer'}
            </Button>
          </form>
        </Form>
      </CardContent>
    </Card>
  );
}
