"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, useQuery, useQueryClient } from "@tanstack/react-query";
import MultiSelect from "@/components/ui/FormInput/MultiSelectNew";
import { Button } from "@/components/ui/button";

import {
  addAssignCollection,
  editAssignCollection,
} from "@/Services/AssignCollections/ApiAssignCollections";
import { getProductCollections } from "@/Services/ProductCollections/ApiProductCollections";
import { Loader2 } from "lucide-react";

// const schema = yup.object().shape({
//   page: yup.string().required("Page is required"),
//   section_type: yup.string().required("Section is required"),
//   collections_ids: yup
//     .array()
//     .min(1, "Collections is required")
//     .required("collections is required"),
// });

const schema = yup.object().shape({
  page: yup.string().required("Page is required"),
  section_type: yup.string().required("Section is required"),
  collection_ids: yup
    .array()
    .when("section_type", {
      is: "3-box-section",
      then: (schema) =>
        schema
          .length(3, "Exactly 3 collections must be selected for 3-box section")
          .required(),
    })
    .when("section_type", {
      is: "combo-box",
      then: (schema) =>
        schema
          .min(2, "Select at least 2 collections for Combo Box")
          .max(4, "You can select up to 4 collections for Combo Box")
          .required(),
    })
    .when("section_type", {
      is: (val) => val && !["3-box-section", "combo-box"].includes(val),
      then: (schema) =>
        schema.length(1, "Exactly 1 collection must be selected").required(),
    }),
});

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

  const {
    control,
    handleSubmit,
    reset,
    setValue,
    watch,
    getValues,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
    defaultValues: {
      page: "/",
    },
  });
  const sectionWatch = watch("section_type");

  useEffect(() => {
    if (type === "edit" && editData) {
      Object.keys(editData).forEach((key) => {
        if (key === "visibility" && typeof editData.visibility === "object") {
          const visibility = editData?.visibility;
          Object?.keys(visibility)?.forEach((vKey) => {
            setValue(vKey, visibility[vKey] ? true : false);
          });
        } else {
          setValue(key, editData[key]);
        }
      });
    }
  }, [type, editData, setValue]);

  const { data: collections = [], isLoading: isCollectionLoading } = useQuery({
    queryKey: ["products_collections"],
    queryFn: () => getProductCollections(),
  });

  const addMutation = useMutation({
    mutationFn: addAssignCollection,
    onSuccess: () => {
      queryClient.invalidateQueries("assign_collections");
      reset();
    },
  });

  const editMutation = useMutation({
    mutationFn: (data) => editAssignCollection(data, editData.id),
    onSuccess: () => {
      queryClient.invalidateQueries("assign_collections");
      reset();
      onClose();
    },
  });

  const submitHandler = (data) => {
    const payload = {
      ...data,
      collection_ids: JSON.stringify(data.collection_ids || []),
    };

    if (type === "add") {
      addMutation.mutate(payload);
    } else {
      payload.id = editData?.id;
      editMutation.mutate(payload);
    }
  };

  if (isCollectionLoading) {
    return (
      <div className="flex items-center justify-center h-48">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  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"} Assign Collection
        </h2>
      </div>

      <form onSubmit={handleSubmit(submitHandler)} className="p-6 space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <Controller
            name="page"
            control={control}
            render={({ field }) => (
              <MultiSelect
                {...field}
                label="Page"
                options={[{ label: "Home", value: "/" }]}
                errors={errors}
                required
                disabled
              />
            )}
          />
          <Controller
            name="section_type"
            control={control}
            render={({ field }) => (
              <MultiSelect
                {...field}
                label="Section Type"
                options={[
                  { label: "3 Box Section", value: "3-box-section" },
                  { label: "Combo Box", value: "combo-box" },
                  { label: "Scroll - Top", value: "scroll-top" },
                  { label: "Scroll - Bottom", value: "scroll-bottom" },
                ]}
                errors={errors}
                required
              />
            )}
          />

          <div className="col-span-full">
            {/* <Controller
              name="collection_ids"
              control={control}
              render={({ field }) => {
                return (
                  <MultiSelect
                    {...field}
                    label={`Select Collections`}
                    options={collections?.rows?.map((p) => ({
                      label: p.name,
                      value: p.id,
                    }))}
                    isMulti
                    isSearchable
                    showClearAll
                    errors={errors}
                    required
                    selectable
                    draggable
                    disabled={!getValues("section_type")}
                  />
                );
              }}
            /> */}
            <Controller
              name="collection_ids"
              control={control}
              render={({ field }) => {
                const sectionType = getValues("section_type");

                let helperText = "";
                if (sectionType === "3-box-section") {
                  helperText = "Select exactly 3 collections.";
                } else if (sectionType === "combo-box") {
                  helperText = "Select between 2 and 4 collections.";
                } else if (sectionType) {
                  helperText = "Select exactly 1 collection.";
                }

                return (
                  <MultiSelect
                    {...field}
                    label={`Select Collections`}
                    options={collections?.rows?.map((p) => ({
                      label: p.name,
                      value: p.id,
                    }))}
                    isMulti
                    isSearchable
                    showClearAll
                    errors={errors}
                    required
                    selectable
                    draggable
                    disabled={!getValues("section_type")}
                    helperText={helperText} 
                  />
                );
              }}
            />
          </div>
        </div>

        <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 AddAssignCollections;
