import { useState } from 'react'
import { z } from 'zod'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { useMutation } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { Loader2, LogIn } from 'lucide-react'
import { toast } from 'sonner'
import { useAuthStore } from '@/stores/auth-store'
import { login } from '@/lib/api/auth'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { PasswordInput } from '@/components/password-input'

const formSchema = z.object({
  email: z.email({
    error: (iss) => (iss.input === '' ? 'E-posta giriniz' : undefined),
  }),
  password: z
    .string()
    .min(1, 'Sifre giriniz')
    .min(6, 'Sifre en az 6 karakter olmalidir'),
})

interface UserAuthFormProps extends React.HTMLAttributes<HTMLFormElement> {
  redirectTo?: string
}

export function UserAuthForm({
  className,
  redirectTo,
  ...props
}: UserAuthFormProps) {
  const [isLoading, setIsLoading] = useState(false)
  const navigate = useNavigate()
  const { auth } = useAuthStore()

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      email: '',
      password: '',
    },
  })

  const signInMutation = useMutation({
    mutationFn: login,
    onSuccess: ({ token, user }) => {
      auth.setUser(user)
      auth.setAccessToken(token)
      toast.success(`Hos geldiniz, ${user.name}`)
      // Wait for Zustand state to fully propagate before navigating
      setTimeout(() => {
        navigate({ to: redirectTo || '/', replace: true })
      }, 0)
    },
    onSettled: () => {
      setIsLoading(false)
    },
  })

  async function onSubmit(data: z.infer<typeof formSchema>) {
    setIsLoading(true)

    await signInMutation.mutateAsync(data)
  }

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(onSubmit)}
        className={cn('grid gap-3', className)}
        {...props}
      >
        <FormField
          control={form.control}
          name='email'
          render={({ field }) => (
            <FormItem>
              <FormLabel className='text-white/70'>E-posta</FormLabel>
              <FormControl>
                <Input
                  placeholder='yonetici@bogazici.com.tr'
                  className='border-white/10 bg-white/5 text-white placeholder:text-white/30 focus-visible:border-white/25 focus-visible:ring-0'
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name='password'
          render={({ field }) => (
            <FormItem className='relative'>
              <FormLabel className='text-white/70'>Sifre</FormLabel>
              <FormControl>
                <PasswordInput
                  placeholder='Sifrenizi girin'
                  className='border-white/10 bg-white/5 text-white placeholder:text-white/30 focus-visible:border-white/25 focus-visible:ring-0'
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button
          className='mt-3 h-11 rounded-xl bg-[#3b7ddd] text-white hover:bg-[#2d6bc4]'
          disabled={isLoading}
        >
          {isLoading ? <Loader2 className='animate-spin' /> : <LogIn />}
          Oturum ac
        </Button>

        <div className='rounded-xl border border-white/8 bg-white/5 px-4 py-3 text-xs text-white/40'>
          Eger yetki sorunu yasarsaniz sistem yoneticinizden yeni rol ve
          permission atamasi talep edin.
        </div>
      </form>
    </Form>
  )
}
