import axios from "axios";
import { motion } from "framer-motion";
import React, { useEffect, useState, useCallback } from "react";

interface PopupDialogProps {
  onCloseColor: (
    brand: string,
    attributeId: string,
    buttonType: string
  ) => void;
  category: string;
  subCategory: string;
}

const AddColorModal: React.FC<PopupDialogProps> = ({
  onCloseColor,
  category,
  subCategory,
}) => {
  const [input, setInput] = useState<string>("");
  const [attributes, setAttributes] = useState<any>([]);

  const handleBrandChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInput(e.target.value);
  };

  const handleSubmit = (buttonType: string) => {
    let _attributeId = attributes.find((e: any) => e.attributeName === "Color");
    // console.log(_attributeId?._id)
    onCloseColor(input, _attributeId._id, buttonType);
  };

  const getAttributes = useCallback(async () => {
    const res = await axios.get(
      `https://api.jazzagain.com/public/index.php/api/getAttributes?categoryId=${category}&subCategoryId=${subCategory}`
    );
    setAttributes(res.data.attributes);
    console.log(res.data.attributes);
  }, [category, subCategory]);

  useEffect(() => {
    getAttributes();
  }, [getAttributes]);

  return (
    <div className="fixed inset-0 flex justify-center items-center z-50">
      <div className="absolute inset-0 bg-black opacity-50"></div>
      <div className="max-w-lg z-10">
        <motion.div
          initial={{ y: -300 }}
          animate={{ x: 0, y: 0 }}
          transition={{ duration: 0.5 }}
          className="bg-white shadow-lg rounded-lg p-[1.5rem] sm:p-[3rem]"
        >
          <h2 className="text-xl font-semibold mb-4">Product Color</h2>

          <div className="text-sm my-4">
            <label htmlFor="Nbrand">Color *</label>
            <input
              type="text"
              name="brand"
              id="brand"
              className="w-full p-2 rounded-lg border border-gray-300 mt-1"
              onChange={handleBrandChange}
            />
          </div>
          <div className="flex space-x-2 justify-around">
            <button
              onClick={() => handleSubmit("cancel")}
              className="w-full p-2 rounded-lg bg-[#383736] hover:bg-[#FE342B] text-white"
            >
              Cancel
            </button>
            <button
              onClick={() => handleSubmit("submit")}
              className="w-full p-2 rounded-lg bg-[#383736] hover:bg-[#FE342B] text-white"
            >
              Submit
            </button>
          </div>
        </motion.div>
      </div>
    </div>
  );
};

export default AddColorModal;
