"use client"

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

import { SubmitButton } from "@/components/forms/submitButton"
import { RecipientDepartment } from "@/generated/prisma/client"
import {
  createNewRecipient,
  updateRecipient,
} from "@/lib/actions/recipient.actions"
import {
  CreateRecipientFormType,
  recipientSchema,
  UpdateRecipientFormType,
} from "@/lib/schemas/recipients.schemas"
import { Recipient } from "@/lib/types"

interface RecipientFormProps {
  initialData?: Recipient
  mode?: "create" | "edit"
}

export default function RecipientForm({
  initialData,
  mode = "create",
}: RecipientFormProps) {
  const router = useRouter()

  const {
    register,
    handleSubmit,
    setError,
    formState: { errors, isSubmitting, isSubmitSuccessful },
  } = useForm<CreateRecipientFormType>({
    resolver: zodResolver(recipientSchema),
    defaultValues: {
      id: initialData?.id || "",
      username: initialData?.username || "",
      firstName: initialData?.firstName || "",
      lastName: initialData?.lastName || "",
      department: initialData?.department || "OTHER",
      email: initialData?.email || "",
      phone: initialData?.phone || "",
    },
  })

  const onSubmit = async (formData: CreateRecipientFormType) => {
    const response =
      mode === "create"
        ? await createNewRecipient(formData)
        : await updateRecipient(formData as UpdateRecipientFormType)

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

    if (response?.success) {
      toast.success(response.message)
      router.push("/recipients")
    }
  }

  return (
    <form className="flex flex-col gap-4" onSubmit={handleSubmit(onSubmit)}>
      <input type="hidden" {...register("id")} />
      <div>
        <label htmlFor="username" className="mb-2 block text-lg">
          Username
        </label>
        <input
          type="text"
          id="username"
          placeholder="Username"
          {...register("username")}
          className={`w-full rounded-lg border px-4 py-2`}
        />
        {errors?.username && (
          <p className="text-error">{errors.username.message}</p>
        )}
      </div>
      <div>
        <label htmlFor="firstName" className="mb-2 block text-lg">
          First Name
        </label>
        <input
          type="text"
          id="firstName"
          placeholder="First Name"
          {...register("firstName")}
          className={`w-full rounded-lg border px-4 py-2`}
        />
        {errors?.firstName && (
          <p className="text-error">{errors.firstName.message}</p>
        )}
      </div>
      <div>
        <label htmlFor="lastName" className="mb-2 block text-lg">
          Last Name
        </label>
        <input
          type="text"
          id="lastName"
          placeholder="Last Name"
          {...register("lastName")}
          className={`w-full rounded-lg border px-4 py-2`}
        />
        {errors?.lastName && (
          <p className="text-error">{errors.lastName.message}</p>
        )}
      </div>
      <div>
        <label htmlFor="department" className="mb-2 block text-lg">
          Department
        </label>
        <select
          id="department"
          {...register("department")}
          className="w-full rounded-lg border px-4 py-2"
        >
          <option value="">Select a department</option>
          {Object.keys(RecipientDepartment).map((department) => (
            <option key={department} value={department}>
              {department}
            </option>
          ))}
        </select>
        {errors?.department && (
          <p className="text-error">{errors.department.message}</p>
        )}
      </div>
      <div>
        <label htmlFor="email" className="mb-2 block text-lg">
          Email
        </label>
        <input
          type="text"
          id="email"
          placeholder="Email"
          {...register("email")}
          className={`w-full rounded-lg border px-4 py-2`}
        />
        {errors?.email && <p className="text-error">{errors.email.message}</p>}
      </div>
      <div>
        <label htmlFor="phone" className="mb-2 block text-lg">
          Phone
        </label>
        <input
          type="text"
          id="phone"
          placeholder="Phone"
          {...register("phone")}
          className={`w-full rounded-lg border px-4 py-2`}
        />
        {errors?.phone && <p className="text-error">{errors.phone.message}</p>}
      </div>
      <SubmitButton
        isSubmitting={isSubmitting}
        isSubmitSuccessful={isSubmitSuccessful}
      >
        {mode === "create" ? "Create Recipient" : "Update Recipient"}
      </SubmitButton>
    </form>
  )
}
