"use client"

import { zodResolver } from "@hookform/resolvers/zod"
import { useRouter, useSearchParams } from "next/navigation"
import { useState } from "react"
import { useForm } from "react-hook-form"

import { Button } from "@/components/ui/button"
import { signInAction } from "@/lib/actions/auth.actions"
import { SignInFormType, signInSchema } from "@/lib/schemas/auth.schemas"

export default function SignInForm() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const callbackUrl = searchParams.get("callbackUrl")
  const [error, setError] = useState<string | null>(null)

  const { register, handleSubmit, formState } = useForm<SignInFormType>({
    resolver: zodResolver(signInSchema),
    defaultValues: {
      username: "",
      password: "",
    },
  })

  const onSubmit = async (values: SignInFormType) => {
    const response = await signInAction(values)

    if (response?.success) {
      router.push(callbackUrl || "/")
    }

    if (response?.error) {
      setError(response.error)
    }
  }

  return (
    <form className="flex flex-col gap-4" onSubmit={handleSubmit(onSubmit)}>
      <label className="flex flex-col gap-1">
        Username
        <input
          {...register("username")}
          name="username"
          type="text"
          className="border-input w-full rounded-md border-2 p-2"
        />
        {formState.errors.username && (
          <p className="text-error">{formState.errors.username.message}</p>
        )}
      </label>
      <label className="flex flex-col gap-1">
        Password
        <input
          {...register("password")}
          name="password"
          type="password"
          className="border-input w-full rounded-md border-2 p-2"
        />
        {formState.errors.password && (
          <p className="text-error">{formState.errors.password.message}</p>
        )}
      </label>
      {error && <p className="text-error">{error}</p>}
      <Button type="submit">Sign In</Button>
    </form>
  )
}
