import LayoutWithNav from "@/components/layout/LayoutWithNav";
import StandardContainer from "@/components/layout/StandardContainer";
import { deleteItem, fetchDistricts, myAds } from "apiCalls/apiEndpoints";
import { useDistricts } from "context/DistrictContext";
import { useUser } from "context/UserContext";
import type { NextPage } from "next";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { SyncLoader } from "react-spinners";
import { Tabs, notification } from "antd";

import ProfileLinks from "@/components/layout/ProfileLinks";
import { useMutation, useQuery, useQueryClient } from "react-query";
import { NextSeo } from "next-seo";
import { withAuth } from "auth/withAuth";
import SingleAdWithoutLink from "@/components/ad/SingleAdWithoutLink";
import { usePath } from "context/HistoryContext";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { Button, Modal, Space } from "antd";

const { confirm } = Modal;
const { TabPane } = Tabs;

const Ads: NextPage = ({ data }: any) => {
  const router = useRouter();

  const { setDistricts } = useDistricts();
  const { user, setUser } = useUser();
  const { setpath } = usePath();

  const [pendingads, setpendingads] = useState([]);
  const [activeads, setactiveads] = useState([]);

  const [currentItem, setcurrentItem] = useState(null);

  const queryClient = useQueryClient();

  //get my ads
  const {
    data: adsData,
    isLoading: adsDataLoading,
    status,
  } = useQuery(["my-ads"], myAds);

  useEffect(() => {
    if (status === "success") {
      setpendingads(adsData?.data.filter((ad: any) => ad.verified === 0));
      setactiveads(adsData?.data.filter((ad: any) => ad.verified === 1));
    }
  }, [adsData?.data, status]);

  //delete an advert
  const { mutate: deleteItemMn, isLoading: isDeletingItem } = useMutation(
    deleteItem,
    {
      onSuccess: (data) => {
        // router.reload();
        queryClient.invalidateQueries("my-ads");
        
        notification.success({
          message: "Ad Deleted Successfully",
        });
      },
      onError: (err) => {
        console.log(err);
        notification.error({
          message: "Error",
          description: "Your Ad cannot be deleted at this time",
        });
      },
    }
  );

 

  // const router = useRouter();
  // const { user, setUser } = useUser();
  // const token = getToken();

  // np(() => {

  //   if (
  //     token === null ||
  //     !token || // 👈 null and undefined check
  //     Object.keys(token).length === 0
  //   ) {
  //     router.push("/login");
  //   }
  // }, [token, router]);

  // useEffect(() => {
  //   console.log("adsData", adsData);
  // }, [adsData]);

  // useEffect(() => {
  //   setDistricts(data?.districts);
  // console.log(data?.districts);
  // }, [data?.districts, setDistricts]);

  // const [isLoading, setIsLoading] = useState(true);

  // if (adsDataLoading) {
  //   return (
  //     <div className="center mt-10">
  //       <SyncLoader color="green" size={5} />
  //     </div>
  //   );
  // }

  const onChange = (key: string) => {
    console.log(key);
  };

  const deleteAd = () => {};

  return (
    <LayoutWithNav page_title="my-ads" description="my-ads">
      <NextSeo title={`My Ads | Ashantiweb.com`} description={`My Ads`} />
      <StandardContainer>
        {/* mobile version */}
        {/* {adsDataLoading ? (
          <LoadingIndicator />
        ) : (
          <div className="flex mt-10">
            <div className="md:block lg:w-3/12">
              <ProfileLinks />
            </div>
          </div>
        )} */}
        {/* ./mobile version */}

        {/* desktop version */}
        {adsDataLoading ? (
          <div className="center">
            <SyncLoader color="green" size={10} />
          </div>
        ) : (
          <div className="flex flex-col md:flex-row mt-10">
            <div className="w-full lg:w-3/12">
              <ProfileLinks />
            </div>
            <div className="w-full lg:w-9/12 pl-2">
              <Tabs defaultActiveKey="1" onChange={onChange}>
                {/* change the condition for each one of these */}
                <TabPane tab={`Active Ads (${activeads.length})`} key="1">
                  {activeads.length <= 0 && "You have no active ads"}
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-4 w-full">
                    {adsData?.data
                      ?.filter((ad: any) => ad.verified === 1)
                      ?.map((ad: any, index: number) => (
                        <>
                          <SingleAdWithoutLink
                            isDeletingItem={isDeletingItem}
                            ad={ad}
                            index={index}
                            currentItem={currentItem}
                            deleteItemMn={deleteItemMn}
                            setcurrentItem={setcurrentItem}
                          />
                        </>
                      ))}
                  </div>
                </TabPane>
                <TabPane tab={`Pending Ads (${pendingads.length})`} key="2">
                  {pendingads.length <= 0 && "You have no Pending ads"}
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-4 w-full">
                    {adsData?.data
                      .filter((ad: any) => ad.verified === 0)
                      ?.map((ad: any, index: number) => (
                        <>
                          <SingleAdWithoutLink
                            isDeletingItem={isDeletingItem}
                            ad={ad}
                            index={index}
                            currentItem={currentItem}
                            deleteItemMn={deleteItemMn}
                            setcurrentItem={setcurrentItem}
                          />
                        </>
                      ))}
                  </div>
                </TabPane>
                {/* <TabPane tab="Declined Ads" key="3">
                {pendingads.length <= 0 && "You have no declined ads"}
              </TabPane> */}
                <TabPane tab={`All Ads (${adsData.data.length})`} key="4">
                  {adsData.data.length <= 0 && "You have no ads"}
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-4 w-full">
                    {adsData.data?.map((ad: any, index: number) => (
                      <>
                        <SingleAdWithoutLink
                          isDeletingItem={isDeletingItem}
                          ad={ad}
                          index={index}
                          currentItem={currentItem}
                          deleteItemMn={deleteItemMn}
                          setcurrentItem={setcurrentItem}
                        />
                      </>
                    ))}
                  </div>
                </TabPane>
              </Tabs>
            </div>
          </div>
        )}
        {/* ./desktop version */}
      </StandardContainer>
    </LayoutWithNav>
  );
};

export async function getServerSideProps({ req, res }: any) {
  // res.setHeader(
  //   "Cache-Control",
  //   "public, s-maxage=10, stale-while-revalidate=59"
  // );

  const districts = await fetchDistricts();

  return {
    props: {
      data: { districts: districts.data },
    }, // will be passed to the page component as props
  };
}

export default withAuth(Ads);
