"use client";

import React, { useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { useMutation, useQueryClient } from "@tanstack/react-query";

import CustomInput from "@/components/ui/FormInput/CustomInput";
import { CustomDropZone } from "@/components/ui/FormInput/Inputs";
import { Button } from "@/components/ui/button";
import { addScheme, editScheme } from "@/Services/Schemes/ApiSchemes";

const schema = yup.object().shape({
  name: yup.string().required("Scheme name is required"),
  alias: yup.string().required("Alias is required"),
  image: yup.mixed().nullable(),
});

const AddScheme = ({ type = "add", editData, onClose }) => {
  const queryClient = useQueryClient();

  const {
    control,
    handleSubmit,
    reset,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
    defaultValues: {},
  });

  const [imageFile, setImageFile] = useState({
    image: editData?.image ? [editData.image] : [],
  });

  useEffect(() => {
    setValue("image", imageFile);
  }, [imageFile, setValue]);

  useEffect(() => {
    if (type === "edit" && editData) {
      Object.keys(editData).forEach((key) => {
        setValue(key, editData[key]);
      });

      if (editData.image) {
        setImageFile({ image: [editData.image] });
      }
    }
  }, [type, editData, setValue]);

  const addMutation = useMutation({
    mutationFn: addScheme,
    onSuccess: () => {
      queryClient.invalidateQueries("schemes");
      reset();
      setImageFile({ image: [] });
      onClose?.();
    },
  });

  const editMutation = useMutation({
    mutationFn: (data) => editScheme(data, editData.id),
    onSuccess: () => {
      queryClient.invalidateQueries("schemes");
      reset();
      setImageFile({ image: [] });
      onClose?.();
    },
  });

  const submitHandler = (data) => {
    const formData = new FormData();
    formData.append("folder", "schemes");

    Object.entries(data).forEach(([key, value]) => {
      if (key === "image" && value?.image?.[0]) {
        formData.append("image", value.image[0]);
      } else {
        formData.append(key, value);
      }
    });

    type === "add"
      ? addMutation.mutate(formData)
      : editMutation.mutate(formData);
  };

  return (
    <div className="bg-white pt-0 w-full border border-gray-200 rounded-md ">
      <div className="flex justify-between items-center border-b p-4 bg-brand-dark/5">
        <h2 className="text-xl font-semibold text-brand-dark">
          {type === "add" ? "Add" : "Edit"} Scheme
        </h2>
      </div>

      <form onSubmit={handleSubmit(submitHandler)} className="p-6 space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <Controller
            name="name"
            control={control}
            render={({ field }) => (
              <CustomInput
                {...field}
                label="Scheme Name"
                type="text"
                value={field.value}
                errors={errors}
                placeholder="Enter scheme name"
                required
              />
            )}
          />
          <Controller
            name="alias"
            control={control}
            render={({ field }) => (
              <CustomInput
                {...field}
                label="Alias Name"
                type="text"
                value={field.value}
                errors={errors}
                placeholder="Enter scheme alias"
                required
              />
            )}
          />
        </div>

        <CustomDropZone
          name="image"
          label="Scheme Image"
          number_of_images={1}
          errors={errors}
          fileType={"image"}
          image_size={1024 * 1024 * 2}
          uploadedFiles={imageFile}
          setUploadedFiles={setImageFile}
          showIcon={false}
          required
        />

        <div className="flex justify-end gap-2 pt-4">
          <Button onClick={() => reset()} type="reset" className="bg-red-700">
            Reset
          </Button>
          <Button type="submit" variant="dark">
            Save
          </Button>
        </div>
      </form>
    </div>
  );
};

export default AddScheme;
