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

const schema = z.object({
  username: z
    .string()
    .min(3, { message: "Username must be at least 3 characters long!" })
    .max(20, { message: "Username must be at most 20 characters long!" }),
  email: z.string().email({ message: "Invalid email address!" }),
  password: z
    .string()
    .min(8, { message: "Password must be at least 8 characters long!" }),
  groupName: z.string().min(1, { message: "Group name is required!" }),
  groupLeader: z.string().min(1, { message: "Group leader name is required!" }),
  description: z.string().min(1, { message: "Group description is required!" }),
  meetingDay: z.string().min(1, { message: "Group meeting day is required!" }),
  meetingTime: z.string().min(1, { message: "Meeting time is required!" }),
  venue: z.string({ message: "Meeting venue is required!" }),
  img: z.instanceof(File, { message: "Image is required" }),
});

type Inputs = z.infer<typeof schema>;

const CellGroupForm = ({
  type,
  data,
}: {
  type: "create" | "update";
  data?: any;
}) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    setValue,
  } = useForm<Inputs>({
    resolver: zodResolver(schema),
    defaultValues:{
      username: type === "update" ? data?.username : "",
      email: type === "update" ? data?.email : "",
      password: type === "update" ? data?.password : "",
      groupName: type === "update" ? data?.groupName : "",
      groupLeader: type === "update" ? data?.groupLeader : "",
      description: type === "update" ? data?.description : "",
      meetingDay: type === "update" ? data?.meetingDay : "",
      meetingTime: type === "update" ? data?.meetingTime : "",
      venue: type === "update" ? data?.venue : "",
      img: type === "update" ? data?.img : undefined,
    },
  });

  const onSubmit = handleSubmit((data) => {
    console.log(data);
  });

   React.useEffect(() => {
      if (type === "update" && data?.img) {
        setValue("img", data.img);
      }
    }, [type, data, setValue]);

  return (
    <form className="flex flex-col gap-8" onSubmit={onSubmit}>
      <h1 className="text-xl font-semibold">Create a new Cell Group</h1>
      <span className="text-xs text-gray-400 font-medium">
        Authentication Information
      </span>
      <div className="flex justify-between flex-wrap gap-4">
        <InputField
          label="Username"
          name="username"
          defaultValue={data?.username}
          register={register}
          error={errors?.username}
        />
        <InputField
          label="Email"
          name="email"
          defaultValue={data?.email}
          register={register}
          error={errors?.email}
        />
        <InputField
          label="Password"
          name="password"
          type="password"
          defaultValue={data?.password}
          register={register}
          error={errors?.password}
        />
      </div>
      <span className="text-xs text-gray-400 font-medium">
        Personal Information
      </span>
      <div className="flex justify-between flex-wrap gap-4">
        <InputField
          label="Group Name"
          name="groupName"
          defaultValue={data?.groupName}
          register={register}
          error={errors.groupName}
        />
        <InputField
          label="Group Leader"
          name="groupLeader"
          defaultValue={data?.groupLeader}
          register={register}
          error={errors.groupLeader}
        />
        <InputField
          label="Description"
          name="description"
          defaultValue={data?.description}
          register={register}
          error={errors.description}
        />
        <InputField
          label="Meeting Day"
          name="meetingDay"
          defaultValue={data?.meetingDay}
          register={register}
          error={errors.meetingDay}
        />
        <InputField
          label="Time"
          name="meetingTime"
          defaultValue={data?.meetingTime}
          register={register}
          error={errors.meetingTime}
        />
        <InputField
          label="Venue"
          name="venue"
          defaultValue={data?.location}
          register={register}
          error={errors.venue} 
        />
        
        <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>
          )}
        </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 CellGroupForm;