"use client"

import { zodResolver } from "@hookform/resolvers/zod"
import { useRouter } from "next/navigation"
import { ChangeEvent } from "react"
import { useForm } from "react-hook-form"
import { toast } from "sonner"

import { SubmitButton } from "@/components/forms/submitButton"
import { importItems } from "@/lib/actions/import.actions"
import { ImportFormType, importSchema } from "@/lib/schemas/import.schemas"
import { CategorySummary } from "@/lib/types"

export default function ImportForm({
  categories,
}: {
  categories: CategorySummary[]
}) {
  const router = useRouter()

  const {
    register,
    handleSubmit,
    setValue,
    setError,
    formState: { errors, isSubmitting, isSubmitSuccessful },
    watch,
  } = useForm<ImportFormType>({
    resolver: zodResolver(importSchema),
    mode: "onSubmit",
  })

  const file = watch("file")

  const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
    const selectedFile = event.target.files?.[0]
    if (selectedFile) {
      setValue("file", selectedFile, { shouldValidate: true })
    }
  }

  const onSubmit = async (formData: ImportFormType) => {
    const response = await importItems(formData)

    if (response?.errors) {
      Object.entries(response.errors).forEach(([fieldName, messages]) => {
        messages.forEach((msg: string) => {
          setError(fieldName as keyof ImportFormType, {
            type: "server",
            message: msg,
          })
          toast.error(msg)
        })
      })
      return
    }

    if (response?.success) {
      toast.success(response?.message || "Asset created successfully")
      router.push("/inventory/items")
    }
  }

  return (
    <form className="flex flex-col gap-4" onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label htmlFor="file" className="mb-2 block text-lg">
          File
        </label>
        <input
          type="file"
          accept=".csv"
          onChange={handleFileChange}
          className="w-full rounded-lg border px-4 py-2"
        />
        {errors?.file && <p className="text-error">{errors.file.message}</p>}
      </div>
      <div>
        <label htmlFor="categoryId" className="mb-2 block text-lg">
          Category
        </label>
        <select
          id="categoryId"
          {...register("categoryId")}
          className="w-full rounded-lg border px-4 py-2"
        >
          <option value="">Select a category</option>
          {categories.map((category) => (
            <option key={category.id} value={category.id}>
              {category.name}
            </option>
          ))}
        </select>
        {errors?.categoryId && (
          <p className="text-error">{errors.categoryId.message}</p>
        )}
      </div>
      <SubmitButton
        isSubmitting={isSubmitting}
        isSubmitSuccessful={isSubmitSuccessful}
        disabled={!file}
      >
        Import
      </SubmitButton>
    </form>
  )
}
