import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
import { Button, Radio, RadioChangeEvent } from "antd";
import { useQuery } from "react-query";
import { SyncLoader } from "react-spinners";
import { isEmpty } from "utilFuncs/utilFunctions";
import { Checkbox } from "antd";
import { CheckboxChangeEvent } from "antd/es/checkbox";
import Link from "next/link";
import { fetchSubFieldsClient } from "apiCalls/apiEndpoints";
// import Checkbox from "antd/es/checkbox";

function  Filters({
  categoryFilterFields,
  setPrice,
  setMinPrice,
  setMaxPrice,
}: any) {
  //router
  const router = useRouter();

  const { ads_category } = router.query;

  // let subClassifieds = categoryFilterFields?.subclassifieds;

  const [subClassifieds, setsubClassifieds] = useState([]);

  // console.log('category filter fields', categoryFilterFields)

  const [isShowAll, setIsShowAll] = useState(false);

  const [currentFilterTtemId, setcurrentFilterTtemId] = useState();

  const [sortOptionsLocal, setsortOptionsLocal] = useState<any>([]);

  useEffect(() => {
    console.log("sort options local", sortOptionsLocal);
  }, [sortOptionsLocal]);

  const { data, isLoading, isSuccess, status } = useQuery(
    ["sort-options-query", ads_category],
    fetchSubFieldsClient
  );

  function sortCategories(a, b) {
    const categoryOrder = [
      "laptops-computers",
      "mobile-phones-and-tablets",
      "tv-dvd-equipment",
      "audio-music-equipment",
      "security-surveilance",
      "computer-accessories",
      "computer-hardware",
      "networking-products",
      "photo-video-cameras",
      "security-surveilance",
      "accessories-supplies-for-electronics",
      "video-game-consoles",
      "printers-and-scanners",
      "headphones",
      "software"
    ];

    console.log("sorting...");

    return categoryOrder.indexOf(a.slug) - categoryOrder.indexOf(b.slug);
  }

  useEffect(() => {
    if (isSuccess) {
      
      setcurrentFilterTtemId(null);


      // Sort the categories array using the custom sorting function
      const sortedCategories =
        data.data.data.subclassifieds.sort(sortCategories);

      

      setsubClassifieds(sortedCategories);

      const json = JSON.parse(data.data.data?.sort_options ?? "[]");
      setsortOptionsLocal(json[2]?.custom_sort ?? []);
    }
  }, [status, isSuccess, data?.data]);

  const [queryObj, setqueryObj] = useState<any>({});

  useEffect(() => {
    if (!isEmpty(queryObj)) {
      router.push({
        pathname: ads_category?.toString(),
        query: queryObj,
      });
    }
  }, [queryObj]);

  const applyClickedFilter = (e: any, sbc: any) => {
   
    setcurrentFilterTtemId(sbc.id);
    setIsShowAll(false);
    // setqueryObj({});
    // setqueryObj((prev: any) => {
    //   return {
    //     ...prev,
    //     type: sbc.slug,
    //   };
    // });

    // data?.data.data.subclassifieds.find((item : any) => item.slug === sbc.slug)
    const json = JSON.parse(
      subClassifieds.find((item: any) => item.slug === sbc.slug)
        ?.sort_options ?? "[]"
    );
    setsortOptionsLocal(json[2]?.custom_sort ?? []);
  };

  const showAllHandler = () => {
    setIsShowAll(!isShowAll);
    router.push(`${ads_category}`);
  };

  const onChangeConditionType = (label: string, e: any) => {
    setqueryObj((prev: any) => {
      return { ...prev, [label]: e.target.value };
    });
  };

  const onChangeProductType = (label: string, e: any) => {
    console.log(e);

    // let f = {}
    // f[label]: e.target.value
    // setSpaceType(e.target.name)
    setqueryObj((prev: any) => {
      return { ...prev, [label]: e.target.value };
    });
  };

  const onChange = (e: CheckboxChangeEvent) => {
    console.log(`checked = ${e.target.checked}`);
  };

  //hangle the price changes
  const [price, setprice] = useState(1);
  
  const onPriceChange = (e: RadioChangeEvent) => {
    console.log("radio checked", e.target.value);
    setPrice(e.target.value);
  };

  return (
    <div className="space-y-4">
      {/* location */}
      {subClassifieds?.length > 0 && (
        <div className="bg-white rounded-md shadow-md p-3">
          <p className="font-normal text-gray-600">Filters</p>
          <ul className="mt-2">
            {/* <li
            className={`cursor-pointer text-gray-500 ${
              isShowAll ? "font-bold" : ""
            }`}
            onClick={() => showAllHandler()}
          >
            Show all
          </li> */}
            {subClassifieds?.map((sbc: any) => (
              <>
                {/* <Radio key={sbc.id} value={sbc.slug}>{sbc.name}</Radio> */}
                <li
                  onClick={(e: any) => {
                    applyClickedFilter(e, sbc);
                    setcurrentFilterTtemId(sbc.id);
                  }}
                  key={sbc.id}
                  className={`cursor-pointer text-gray-500 ${
                    currentFilterTtemId == sbc.id && !isShowAll
                      ? "font-bold"
                      : ""
                  }`}
                  value={sbc.slug}
                >
                  <Link href={`${sbc.slug}`}>
                    <a
                      className={`text-gray-500 ${
                        currentFilterTtemId == sbc.id && !isShowAll
                          ? "font-bold"
                          : ""
                      }`}
                    >
                      {sbc.name}
                    </a>
                  </Link>
                </li>
              </>
            ))}
          </ul>
        </div>
      )}

      {ads_category != "jobs-in-ashanti" && (
        <div className="bg-white rounded-md shadow-md p-3">
          <p className="font-normal text-gray-600">Price, GHC</p>
          <div className="flex flex-col sm:flex-row justify-content-start items-center mt-2">
            <input
              type="number"
              placeholder="min"
              onChange={(e) => {
                if (e.target.value.length > 0) {
                  setMinPrice(e.target.value);
                } else {
                  setMinPrice(0);
                }
              }}
              className="w-20 border-2 p-2 rounded-sm inline-block"
            />{" "}
            <div className="mx-6">-</div>
            <input
              type="number"
              placeholder="max"
              onChange={(e) => {
                if (e.target.value.length > 0) {
                  setMaxPrice(e.target.value);
                } else {
                  setMaxPrice(0);
                }
              }}
              className="w-20 border-2 p-2 rounded-sm inline-block"
            />
          </div>

          {/* price  */}

          <div className="mt-2">
            <Radio.Group name="price" onChange={onPriceChange}>
              <Radio value={90}>Under 90 </Radio>
              <br />
              <Radio value={700}>90 - 800 </Radio>
              <br />
              <Radio value={800}>800 - 2.7 K </Radio>
              <br />
              <Radio value={2700}>2.7 - 8.4 K </Radio>
              <br />
              <Radio value={8400}>More than 8.4 K </Radio>
            </Radio.Group>
            <br />
            {/* <Button type="primary" onChange={applyPriceChanges}>Apply filters</Button> */}
            {/* <button className="bg-blue-500">apply filter</button> */}
          </div>
        </div>
      )}

      {/* end price change */}

      {/* property type */}
      {/* {ads_category === "property" && (
        <div className="bg-white rounded-md shadow-md p-3">
          <p className="font-normal text-gray-600">Property Type</p>
          <div className="flex justify-content-start items-center mt-2">
            <input
              type="text"
              placeholder="Find property type"
              className="w-full border-2 p-2 rounded-sm inline-block"
            />{" "}
          </div>

          <div className="mt-2 h-1 overflow-auto">
            <Checkbox onChange={onChange}>Apartments</Checkbox>
            <br />
            <Checkbox onChange={onChange}>Apartments</Checkbox>
            <br />
            <Checkbox onChange={onChange}>Apartments</Checkbox>
            <br />
            <Checkbox onChange={onChange}>Apartments</Checkbox>
            <br />
            <Checkbox onChange={onChange}>Apartments</Checkbox>
          </div>
        </div>
      )} */}

      {/* end property type */}

      {/* {sortOptionsLocal.length > 0 && (
        <div className="bg-white rounded-md shadow-md p-3">
          <p className="font-normal text-gray-600">
            {sortOptionsLocal[0]?.label}
          </p>
          <ul className="">
            <Radio.Group
              name={sortOptionsLocal[0]?.label}
              onChange={(e) =>
                onChangeProductType(sortOptionsLocal[0]?.label, e)
              }
            >
              {sortOptionsLocal[0]?.options.map((sbc: any) => (
                <>
                  <Radio key={sbc.value} value={sbc.value}>
                    {sbc.label}
                  </Radio>
                  <br />
                </>
              ))}
            </Radio.Group>
          </ul>
        </div>
      )} */}

      {/* {sortOptionsLocal.length > 0 && (
        <div className="bg-white rounded-md shadow-md p-3">
          <p className="font-normal text-gray-600">
            {sortOptionsLocal[1]?.label}
          </p>
          <ul className="">
            <Radio.Group
              name={sortOptionsLocal[1]?.label}
              onChange={(e) =>
                onChangeConditionType(sortOptionsLocal[1]?.label, e)
              }
            >
              {sortOptionsLocal[1]?.options.map((sbc: any) => (
                <>
                  <Radio key={sbc.value} value={sbc.value}>
                    {sbc.label}
                  </Radio>
                  <br />
                </>
              ))}
            </Radio.Group>
          </ul>
        </div>
      )} */}

      {/* sort options loop */}
      {sortOptionsLocal.length > 0 &&
        sortOptionsLocal.map((item) => (
          <>
            <div className="bg-white rounded-md shadow-md p-3 mt-8">
              <p className="font-normal text-gray-600">{item?.label}</p>
              <ul className="w-full h-40 overflow-auto mt-3">
                {/* <Radio.Group
                  name={item?.label}
                  onChange={(e) => onChangeConditionType(item?.label, e)}
                > */}
                {item?.options.map((sbc: any) => (
                  <>
                    <Checkbox
                      key={sbc.value}
                      value={sbc.value}
                      onChange={(e) => {
                        console.log(e.target.value);
                        setqueryObj({
                          type: e.target.value,
                        });
                      }}
                    >
                      {sbc.label}
                    </Checkbox>
                    <br />
                  </>
                ))}
              </ul>
            </div>
          </>
        ))}
      {/* end sort options loop */}

      <Button
        type="default"
        onClick={() => {
          router.push(`/ads/${ads_category}`);
        }}
      >
        Clear Filters
      </Button>
    </div>
  );
}

export default Filters;
