import { Button, Input, Select, Skeleton, Space, Table } from "antd";
import cx from "classnames";
import { FC, useContext, useEffect, useState } from "react";
import styles from "./myWishList.module.scss";
import {
  SearchOutlined,
  FilterFilled,
  DeleteOutlined,
  ShoppingCartOutlined
} from "@ant-design/icons";
import ListView from "../../products/productCard/ListView";
import * as wishList from "../../../pages/api/wishList";
import type { ColumnsType } from "antd/es/table";
import _, { constant } from "lodash";
import * as AddToCardApi from "../../../pages/api/addTocart";
import * as CartApi from "../../../pages/api/cart";
import * as CommonApi from "../../../pages/api/common";
import * as ShipApi from "../../../pages/api/ship";
import InternalPageHeader from "../../internalPageHeader/InternalPageHeader";
import shopConetxt from "../../../context/shopConetxt";
import CartModal from "../../modal/cartModal/CartModal";
import Link from "next/link";
import { APIKEY, baseUrl } from "../../../constants/urls";
import Geocode from "react-geocode";

interface DataType {
  key: React.Key;
  sno: string;
  itemName: string;
  quantity: any;
  price: any;
}

const MyWishList: FC<any> = () => {
  const {
    cart,
    setCartItems,
    setIsCartLoading,
    wishlist,
    removeProductFromWishlist,
  } = useContext(shopConetxt);
  const [product, setProduct] = useState<DataType[]>([]);
  const [newProduct, setNewProduct] = useState<DataType[]>([]);
  const [loginRes, setLoginRes] = useState<any>({});
  const [isCartModalVisible, setIsCartModalVisble] = useState(false);
  const [cartProduct, setCartProduct] = useState([]);
  const [productInvoice, setProductInvoice] = useState<any>({});
  const [value, setValue] = useState("");
  const [latitude, setLatitude] = useState(null);
  const [longitude, setLongitude] = useState(null);
  const [currentAddress, setCurrentAddress] = useState<any>({});
  const [isLoading,setIsLoading] = useState(false);
  const columns: ColumnsType<DataType> = [
    {
      title: "S.No",
      dataIndex: "sno",
      key: "sno",
      render: (text, object, index) => {
        return index + 1;
      },
      responsive: ["xl", "md"],
    },
    {
      title: "",
      dataIndex: "image",
      key: "image",
      render: (text, object: any, index) => {
        return (
          <div className="cursor-pointer">
            <Link href={`/products/details/${object?.url_key}-${object?.product_id}`}>
              {object?.base_image === null ? (
                <img
                  src={baseUrl + "/" + object?.default_image}
                  className={cx(styles.productImageList, "m-2")}
                  alt="thumb"
                />
              ) : (
                <img
                  src={object?.s3_base_url + object?.base_image}
                  className={cx(styles.productImageList, "m-2")}
                  alt="thumb"
                />
              )}
            </Link>
          </div>
        );
      },
      responsive: ["xl", "md"],
    },
    {
      title: "Item Name",
      dataIndex: "itemName",
      key: "itemName",

      sorter: (a: any, b: any) =>
        a.product?.name.localeCompare(b.product?.name),

      render: (text, object: any, index) => {
        return (
          <Link href={`/products/details/${object?.url_key}-${object?.product_id}`}>
            <div className={styles.productName}>{object?.product?.name}</div>
          </Link>
        );
      },
    },
    {
      title: "Price",
      dataIndex: "price",
      key: "price",

      sorter: (a: any, b: any) =>
        a.product?.name.localeCompare(b.product?.name),

      render: (text, object: any, index) => {
        return object?.product?.special_price==null?"-":"₹ " + parseFloat(object?.product?.special_price).toFixed(2);
      },
    },

    {
      title: "Action",
      key: "action",

      render: (_, record: any) => (
        <Space size="middle" className={styles.buttonsSelection}>
          <Button
            type="primary"
            className={styles.buttonsCart}
            onClick={() => {
              AddToCart(record);
            }}
          >
            Move To Cart
          </Button>
          <a
            className={styles.deleteIcon}
            onClick={() => {
              deleteWishList(record);
            }}
          >
            <DeleteOutlined className={styles.buttonDelete} />
          </a>
        </Space>
      ),
      responsive: ["xl", "md"],
    },
    {
      title: "Action",
      key: "action",

      render: (_, record: any) => (
        <Space size="middle" className={styles.buttonsSelection}>
          {/* <Button
            type="primary"
            className={styles.buttonsCart}
            onClick={() => {
              AddToCart(record);
            }}
          >
            Move To Cart
          </Button> */}
          <a onClick={() => {
            AddToCart(record);
          }}

          >
            <ShoppingCartOutlined className={styles.buttonsCartButton} />
          </a>
          <a
            className={styles.deleteIcon}
            onClick={() => {
              deleteWishList(record);
            }}
          >
            <DeleteOutlined className={styles.buttonDelete} />
          </a>
        </Space>
      ),
      responsive: ["xs"],
    },
  ];

  const AddToCart = (record: any) => {

    setIsCartLoading(true);
    const cityPincode = localStorage.getItem("PinCode");
    const lat = loginRes?.data ? currentAddress?.latitude : latitude;
    const long = loginRes?.data ? currentAddress?.longitude : longitude;

    ShipApi.shippingAvailableCheckingAPI(
      loginRes?.token,
      record?.product?.inventory?.source?.pincode,
      cityPincode,
      record?.product?.weight * 1
    ).then((shipRocket) => {
      const params = {
        product_id: record.product_id,
        quantity: 1,
        token: loginRes?.token,
        vendor_id: record.vendor_id,
        mp_seller_id: record.seller_id,
        shipCharge: shipRocket?.rate,
        seller_lat: record?.product?.inventory?.source?.latitude,
        seller_lang: record?.product?.inventory?.source?.longitude,
        customer_lat: lat,
        customer_lang: long,
        item_weight: record?.product?.weight,
        customer_pincode: cityPincode,
        seller_pincode: record?.product?.inventory?.source?.pincode,
        shipping_type: 0
      };
      setIsCartModalVisble(!isCartModalVisible);
      AddToCardApi.addToCart(params).then((res) => {
        const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
        CartApi.cartFetch(tokenData).then((cartRes) => {
          const token = loginRes?.token;
          const id = loginRes?.data?.id;
          getList(token, id,value);
          setIsCartLoading(false);
          if (cartRes.data !== null) {
            setCartItems(cartRes.data);
            <InternalPageHeader item={cartRes.data.items.length} />;
          }
        });
      });


    });
  };
  useEffect(() => {
    setIsLoading(true)
    const val: any = localStorage.getItem("loginDetails");
    const loginDetails = JSON.parse(val);

    setLoginRes(loginDetails);
    const token = loginDetails?.token;
    const id = loginDetails?.data?.id;
    getList(token, id,value);
    const cityPincode = localStorage.getItem("PinCode");
    if (!loginDetails?.data) {
      if (cityPincode !== null) {
        Geocode.setApiKey(APIKEY);
        Geocode.enableDebug();
        Geocode.fromAddress(cityPincode).then(({ results }) => {
          const { lat, lng } = results[0].geometry.location;
          setLatitude(lat);
          setLongitude(lng);
        });
      }
      CommonApi.getRequestWithToken(
        `${baseUrl}/api/customer-pincodes/get-data?token=true&customer_id=${loginDetails?.data?.id}`,
        loginDetails?.token
      ).then((Selectres) => {
        setCurrentAddress(Selectres?.data?.data);
      });
    }
  }, []);

  const getList = (token: any, id: any,searchVal:any) => {
    const cityPincode: any = localStorage.getItem("PinCode");
    // if (cityPincode) {
      wishList.getWishList(token, id, cityPincode,searchVal).then((res:any) => {
        // console.log(res,"res")
        setProduct(res?.data);
        setNewProduct(res?.data);
        setIsLoading(false)
        // const prod: any = [];
        // res?.data.map((product: any, idx: number) => {
        // 	const prodObj = {
        // 		key: idx,
        // 		sno: idx + 1,
        // 		id: product?.product?.id,
        // 		itemName: product?.product?.name,
        // 	};
        // 	prod.push(prodObj);
        // });
        // setProduct(prod);
      });
    // }
  };
  const deleteCart = (productId: any) => {
    const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
    const params = {
      token: tokenData,
      item_id: productId,
    };
    CartApi.removeCartItem(params).then((res_item) => {
      setCartItems(res_item.data);
    });
  };

  const deleteWishList = (record: any) => {
    const params = {
      id: record.product_id,
      token: loginRes?.token,
    };
    wishList.deleteWishList(params).then((res) => {
      removeProductFromWishlist(record.id);
      const token = loginRes?.token;

      getList(token, loginRes?.data?.id,value);
    });
  };

  const searchFunction=(searchVal:any)=>{
    getList(loginRes?.token, loginRes?.data?.id,searchVal);
  }

  return (
    <>
      <div className={cx(styles.wishListContainer)}>
        <h1 className={cx(styles.headerTitle)}>My Wishlist</h1>
        <div>
          <div className={cx("ant-row")}>
            <div className={cx("ant-col ant-col-sm-24 ant-col-xl-16")}>
              <div className={cx("ant-row my-4")}>
                <div className={cx("ant-col ant-col-sm-24 ant-col-xl-8")}>
                  <Input
                    value={value}
                    placeholder="Search "
                    style={{ width: 200 }}
                    allowClear={true}
                    suffix={<SearchOutlined />}
                    size={"middle"}
                    onKeyDown={(event: any) => {

                      if (event.keyCode == 8) {
                        setProduct(newProduct);
                      }
                    }}
                    onChange={(e) => {
                      // if (e.target.value === "") {
                      //   setProduct(newProduct);
                      //   setValue("");
                      // } else {
                      //   const currValue = e.target.value.toLowerCase();
                      //   setValue(currValue);
                      //   const filteredData = product.filter((entry: any) => {
                      //     const name = entry.product?.name.toLowerCase();
                      //     return name.includes(currValue);
                      //   });
                      //   setProduct(filteredData);
                      // }
                      const currValue = e.target.value.toLowerCase();
                        setValue(currValue);
                      searchFunction(e.target.value);
                    }}
                  />
                </div>
                <div className={cx("ant-col ant-col-sm-24 ant-col-xl-8")}>
                  {/* <Select
                    defaultValue="All Category"
                    className={styles.searchDropdown}
                    // onChange={(value) => setSelectedCategory(value)}
                  >
                    <Select.Option value={"All Category"} key={"All Category"}>
                      All Category
                    </Select.Option>
                    {/* {category.map((cat: any) => (
                  <Select.Option value={cat.id} key={cat.id}>
                    {cat.name}
                  </Select.Option>
                ))} 
                  </Select> */}
                </div>
                <div className={cx("ant-col ant-col-sm-24 ant-col-xl-8")}>
                  {/* <Button className={styles.filterBtnMobile}>
                    <div className={styles.filterBtnContent}>
                      <FilterFilled className={cx(styles.filterIcon, `mr-2`)} />
                      Filters
                    </div>
                  </Button> */}
                </div>
              </div>
            </div>
            <div className={cx("ant-col ant-col-sm-24 ant-col-xl-8")} />
          </div>
          {isLoading?<Skeleton/>:<Table
            columns={columns}
            dataSource={product}
            rowKey={(record: any) => {
              return record.id;
            }}
          />}
        </div>
      </div>
      {isCartModalVisible ? (
        <CartModal
          cartLength={cart}
          handleCartClose={() => setIsCartModalVisble(false)}
          products={cart}
          productInvoice={productInvoice}
          deleteCart={deleteCart}
          isCartModalVisible={isCartModalVisible}
          callBack={cart}
        />
      ) : null}
    </>
  );
};

export default MyWishList;
