"use client";
import toast from "@/common/libs/toast";
import { useLoginStore } from "@/common/stores/useLoginStore"
import { Button, Input, Spinner } from "@nextui-org/react"
import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useMemo } from "react";

const Form = () => {
  const { form, updateForm } = useLoginStore()
  const router = useRouter()

  const errorMessage = {
    401: 'Username atau password tidak sesuai',
    404: 'Akun dengan username tersebut tidak ditemukan'
  }

  const mutation = useMutation({
    mutationKey: ['login'],
    mutationFn: async (data: typeof form) => await fetch("/api/auth/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    }),
    onError() {
      toast('Mohon maaf terjadi kesalahan')
    },
    async onSuccess(data) {
      if (data.status !== 200) {
        return toast(errorMessage[data.status as keyof typeof errorMessage])
      }
      router.push('/')
    },
  })

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    updateForm(e.target.name, e.target.value)
  }

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    mutation.mutate(form)
  }

  const isValid = useMemo(() => {
    return form.username && form.password
  }, [form])

  return (
    <form className="grid grid-cols-1 gap-y-4" onSubmit={handleSubmit}>
      <Input
        isRequired
        type="text"
        label="Nama Pengguna"
        name="username"
        onChange={handleInputChange}
        autoFocus
      />
      <Input
        isRequired
        type="password"
        label="Kata Sandi"
        name="password"
        onChange={handleInputChange}
      />
      <Button
        variant="solid"
        color="primary"
        isDisabled={!isValid || mutation.isPending}
        className="mt-2"
        type="submit"
      >
        {mutation.isPending ? <Spinner color="white" size="sm" /> : 'Masuk'}
      </Button>
    </form>
  )
}

export default Form