"use client";

import { createEvent, updateEvent } from "../../../lib/api";

import Image from "next/image";
import InputField from "@/components/InputField";
import React from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";

// Schema handling FileList for img
const schema = z.object({
  title: z.string().min(1, { message: "Title of the event is required!" }),
  description: z.string().min(1, { message: "Description is required!" }),
  eventNumber: z.string().min(1, { message: "Event No is required!" }),
  venue: z.string().min(1, { message: "Address is required!" }),
  date: z.date({ message: "Date of event is required!" }),
  startTime: z.string().min(1, { message: "Start time is required!" }),
  endTime: z.string().min(1, { message: "End time is required!" }),
  img: z
    .any()
    .refine((fileList) => fileList instanceof FileList && fileList.length > 0, {
      message: "Image is required",
    }),
});

type Inputs = z.infer<typeof schema>;

const EventForm = ({
  type,
  data,
}: {
  type: "create" | "update";
  data?: any;
}) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<Inputs>({
    resolver: zodResolver(schema),
    defaultValues: {
      title: type === "update" ? data?.title : "",
      description: type === "update" ? data?.description : "",
      eventNumber: type === "update" ? data?.eventNumber : "",
      venue: type === "update" ? data?.venue : "",
      date: type === "update" ? new Date(data?.date) : new Date(),
      startTime: type === "update" ? data?.startTime : "",
      endTime: type === "update" ? data?.endTime : "",
    },
  });

  const onSubmit = handleSubmit(async (data) => {
    try {
      const formData = new FormData();
      formData.append("title", data.title);
      formData.append("description", data.description);
      formData.append("eventNumber", data.eventNumber);
      formData.append("venue", data.venue);
      formData.append("date", data.date.toISOString());
      formData.append("startTime", data.startTime);
      formData.append("endTime", data.endTime);

      const fileList = data.img as FileList;
      if (fileList.length > 0) {
        formData.append("img", fileList[0]);
      }

      let response;
      if (type === "create") {
        response = await createEvent(formData);
      } else if (type === "update" && data.eventNumber) {
        response = await updateEvent(Number(data.eventNumber), formData);
      }

      if (response?.status === 200) {
        console.log("Event successfully created/updated");
        // Optional: toast / redirect
      } else {
        console.log("Event creation/updating failed");
      }
    } catch (error) {
      console.error("Error during API request", error);
    }
  });

  return (
    <form className="flex flex-col gap-8" onSubmit={onSubmit}>
      <h1 className="text-xl font-semibold">
        {type === "create" ? "Create a new event" : "Update event"}
      </h1>
      <span className="text-xs text-gray-400 font-medium">Event Details</span>

      <div className="flex justify-between flex-wrap gap-4">
        <InputField
          label="Title"
          name="title"
          defaultValue={data?.title}
          register={register}
          error={errors.title}
        />
        <InputField
          label="Description"
          name="description"
          defaultValue={data?.description}
          register={register}
          error={errors.description}
        />
        <InputField
          label="Event No."
          name="eventNumber"
          defaultValue={data?.eventNumber}
          register={register}
          error={errors.eventNumber}
        />
        <InputField
          label="Venue"
          name="venue"
          defaultValue={data?.venue}
          register={register}
          error={errors.venue}
        />
        <InputField
          label="Date"
          name="date"
          defaultValue={data?.date}
          register={register}
          error={errors.date}
          type="date"
        />
        <InputField
          label="Start Time"
          name="startTime"
          defaultValue={data?.startTime}
          register={register}
          error={errors.startTime}
          type="time"
        />
        <InputField
          label="End Time"
          name="endTime"
          defaultValue={data?.endTime}
          register={register}
          error={errors.endTime}
          type="time"
        />

        <div className="flex flex-col gap-2 w-full md:w-1/4 justify-center">
          <label
            className="text-xs text-gray-500 flex items-center gap-2 cursor-pointer"
            htmlFor="img"
          >
            <Image src="/upload.png" alt="" width={28} height={28} />
            <span>Upload a photo</span>
          </label>
          <input type="file" id="img" {...register("img")} className="hidden" />
          {errors.img?.message && (
            <p className="text-xs text-red-400">
              {errors.img.message.toString()}
            </p>
          )}

          {/* Preview for update */}
          {type === "update" && data?.img && typeof data.img === "string" && (
            <div className="pt-2">
              <Image
                src={data.img}
                alt="Existing Event"
                width={100}
                height={100}
                className="rounded-md border"
              />
            </div>
          )}
        </div>
      </div>

      <button className="bg-blue-400 text-white p-2 rounded-md hover:bg-blue-700 transition">
        {type === "create" ? "Create" : "Update"}
      </button>
    </form>
  );
};

export default EventForm;
