"use client";
import { useSearchParams, usePathname, useRouter } from "next/navigation";
import React, { useState } from "react";
import ButtonCustom from "@/components/constantElements/ButtonCustom";
import ImageCustom from "@/components/constantElements/ImageCustom";
import Radio from "@mui/material/Radio";
import RadioGroup from "@mui/material/RadioGroup";
import FormControlLabel from "@mui/material/FormControlLabel";
import FormControl from "@mui/material/FormControl";
import FormLabel from "@mui/material/FormLabel";
import axios from "@/lib/axios";
import { json } from "@remix-run/router";

const CategoryFilter = ({ data }) => {
  const searchParams = useSearchParams();
  const pathName = usePathname();
  const router = useRouter();
  const [pages, setPages] = useState("start");
  const [filterValue, setFilterValue] = useState([]);
  const [radioFilterValue , setRadioFilterValue] = useState(null)
  const [selectValues, setselectValues] = useState(null);
  const [filterValues, setFilterValues] = useState(null);
  const [radioValues, setradioValues] = useState(
    data.items.map(() => {
      return "";
    })
  );


  

  const pageLength = data.items.length - 1;

  const radioChange = (items) => {
    setRadioFilterValue(items.id);
    
    const newArray = [...radioValues];
    newArray[pages] = items.id;
    setradioValues(newArray);

    setselectValues(items);
    const name = Object.keys(items.value)[0];
    const value = Object.values(items.value)[0];

    // setFilterValue((prev) => ({ ...prev, [name]: value }));
    setFilterValue([...filterValue, items.value]);
  };

  const nextHandler = (elem) => {
    setFilterValues(radioFilterValue)
    if (pages < pageLength) {
      setPages((prev) => prev + 1);
    } else {
      setPages(pageLength);
    }
    setselectValues(null);
  };

  const prevHandler = () => {
    if (pages < 1) {
      setPages("start");
    } else {
      setPages((prev) => prev - 1);
    }
    setselectValues(null);
  };
  
  const finalHandler = () => {
    let result = "?";
    filterValue.map((items, i) => {
      const name = Object.keys(items)[0];
      const value = Object.values(items)[0];
        
      if (i === filterValue.length - 1) {
        value.map((valueItems, index , array) => {
          // result += `attr%5B${name}%5D%5B${index}%5D=${valueItems}&`;
          if (index === array.length - 1) {
            result += `attr%5B${name}%5D%5B${index}%5D=${valueItems}`;
          } else {
            result += `attr%5B${name}%5D%5B${index}%5D=${valueItems}&`;
          }
        });
        
      }else {
        value.map((valueItems, index , array) => {
          result += `attr%5B${name}%5D%5B${index}%5D=${valueItems}&`;
          
          // if (index === array.length - 1) {
            
          //   result += `attr%5B${name}%5D%5B${index}%5D=${valueItems}`;
          // } else {
          //   result += `attr%5B${name}%5D%5B${index}%5D=${valueItems}&`;
          // }
        });
      }
      
      
    });


    
    


    // window.history.pushState({}, "", `${result}`);

      
    router.push(`${result}&page=1` , undefined, { scroll: false });
    
    setTimeout(()=>{
      setPages("start")
      setFilterValue([])
      setRadioFilterValue(null)
      setselectValues(null)
      setFilterValues(null)
      setradioValues(data.items.map(() => {
        return "";
      }))
    } , 2000)

  };

  return (
    <div
      className="min-h-[355px] rounded-lg mb-12 overflow-hidden"
      style={{ border: `1px solid ${data.bg_color}` }}
    >
      {pages == "start" ? (
        <>
          {/* head */}
          <div
            className="flex items-center justify-center h-10"
            style={{ backgroundColor: data.bg_color }}
          >
            <div className="text-white font-medium text-lg">
              {data.box_title}
            </div>
          </div>
          {/* head */}

          {/* body */}
          <div
            style={{ height: "calc(355px - 40px)", backgroundColor: "#fff" }}
            className="p-2"
          >
            <div className="grid sm:grid-cols-3 grid-cols-1 gap-2 h-full place-items-center">
              {/* شروع */}
              <div className="col-span-2 h-full flex flex-col justify-center gap-8 place-items-center">
                <div className="text-xl">{data.title}</div>
                <div>
                  <ButtonCustom
                    text={data.start_button}
                    title={data.start_button}
                    color={data.btn_start_color}
                    onClick={() => setPages(0)}
                  />
                </div>
              </div>

              <ImageCustom
                size="original"
                data={data.image}
                alt={data.image_alt}
                title={data.image_alt}
                width={600}
                height={250}
                loading={"lazy"}
              />
              {/* شروع */}
            </div>
          </div>
          {/* body */}
        </>
      ) : (
        <>
          {/* head */}
          <div
            className="flex items-center justify-center h-10"
            style={{ backgroundColor: data.bg_color }}
          >
            <div className="text-white font-medium text-lg">
              {data.items[pages].box_title}
            </div>
          </div>
          {/* head */}

          {/* body */}
          <div
            style={{ height: "calc(300px - 40px)", backgroundColor: "#fff" }}
            className="p-2"
          >
            <div className="grid sm:grid-cols-3 grid-cols-1 gap-2 h-full place-items-center">
              {/* مرحله اول */}
              <div className="col-span-2 h-full flex flex-col gap-8 w-full pr-4">
                <FormControl>
                  <FormLabel id="demo-radio-buttons-group-label">
                    {data.items[pages].title}
                  </FormLabel>
                  <RadioGroup
                    aria-labelledby="demo-radio-buttons-group-label"
                    // defaultValue={data.items[pages].items[0].id}
                    name="radio-buttons-group"
                    value={radioValues[pages]}
                  >
                    {data.items[pages].items.map((items) =>
                      Array.isArray(items.parent) ? (
                        items.parent.map(
                          (radio) =>
                            radio == filterValues && (
                              <FormControlLabel
                                key={items.id}
                                value={items.id}
                                control={<Radio size="small" />}
                                label={items.name}
                                onChange={() => radioChange(items)}
                              />
                            )
                        )
                      ) : (
                        <FormControlLabel
                          key={items.id}
                          value={items.id}
                          control={<Radio size="small" />}
                          label={items.name}
                          onChange={() => radioChange(items)}
                        />
                      )
                    )}
                  </RadioGroup>
                </FormControl>
              </div>

              <ImageCustom
                size="original"
                data={
                  selectValues ? selectValues.image : data.items[pages].image
                }
                alt={
                  selectValues
                    ? selectValues.image_alt
                    : data.items[pages].image_alt
                }
                title={
                  selectValues
                    ? selectValues.image_alt
                    : data.items[pages].image_alt
                }
                width={600}
                height={250}
                loading={"lazy"}
              />
              {/* مرحله اول  */}
            </div>
          </div>
          {/* body */}
        </>
      )}

      {/* buttons */}
      {pages != "start" && (
        <div className="p-2 flex gap-2 justify-center">
          {pages == pageLength ? (
            <ButtonCustom
              text={data.end_button}
              title={data.end_button}
              onClick={finalHandler}
              disabled={radioValues[pages] == "" ? true : false}
              color={radioValues[pages] == "" ? "#a4a4a4" : data.btn_inner_color ?  data.btn_inner_color  : "var(--theme-color)"}
            />
          ) : (
            <ButtonCustom
              disabled={radioValues[pages] == "" ? true : false}
              color={radioValues[pages] == "" ? "#a4a4a4" : "var(--theme-color)"}
              text="مرحله بعد"
              title="مرحله بعد"
              onClick={() => nextHandler(data.items[pages])}
            />
          )}
          <ButtonCustom
            text="مرحله قبل"
            title="مرحله قبل"
            color="#808080"
            onClick={() => prevHandler(data.items[pages])}
          />
        </div>
      )}
    </div>
  );
};

export default CategoryFilter;
