import { FC, useEffect, useState, useContext } from "react";
import styles from "./purchaseOrder.module.scss";
import * as CommonAPI from "../../../pages/api/common";
import { APIKEY, baseUrl, s3BucketUrl } from "../../../constants/urls";
import {
  Button,
  DatePicker,
  Input,
  notification,
  Popconfirm,
  Skeleton,
  Space,
  Table,
} from "antd";
import * as CartApi from "../../../pages/api/cart";
import { useMediaQuery } from "react-responsive";
import {
  SearchOutlined,
  FilterFilled,
  DeleteOutlined,
  DownloadOutlined,
  EyeOutlined,
  MinusCircleTwoTone,
  PlusCircleTwoTone,
  SwapOutlined,
  ShoppingCartOutlined,
} from "@ant-design/icons";
import Geocode from "react-geocode";

import moment from "moment";
import { capitalizeWords } from "../../../constants/commonFunction";
import axios from "axios";
import cx from "classnames";
import { useRouter } from "next/router";
import _ from "lodash";
import shopConetxt from "../../../context/shopConetxt";
import Head from "next/head";
import type { FilterValue, SorterResult } from "antd/es/table/interface";
import type {
  ColumnsType,
  TableProps,
  TablePaginationConfig,
} from "antd/es/table";
import type { DatePickerProps } from "antd";
interface DataType {
  key: React.Key;
  sno: string;
  customerName: string;
  termandConditon: any;
  shipPrice: any;
  estimateDElivery: any;
  items: any;
}

interface TableParams {
  pagination?: TablePaginationConfig;
  sortField?: string;
  sortOrder?: string;
  filters?: Record<string, FilterValue>;
}

const PurchaseOrder: FC<any> = ({ title }) => {
  const {
    cart,
    setCartItems,
    setIsCartLoading,
    productQuantity,
    setProductQuantity,
    deliveryOptions,
    deliveryPriceDetails,
    setDeliveryPriceDetails,
    deliveryDunzoPriceDetails,
    setDeliveryDunzoPriceDetails,
  } = useContext<any>(shopConetxt);
  const [loginRes, setLoginRes] = useState<any>({});
  const [quoteList, setQuoteList] = useState([]);
  const [newQuotation, setNewQuotation] = useState([]);
  const [value, setValue] = useState("");
  const isMobile = useMediaQuery({ maxWidth: 767.68 });
  const [loading, setLoading] = useState(false);
  const [sorter, setSorter] = useState<any>({});
  const [sortOrder, setSortOrder] = useState("desc");
  const [currentAddress, setCurrentAddress] = useState<any>({});
  const router = useRouter();
  const [latitude, setLatitude] = useState(null);
  const [longitude, setLongitude] = useState(null);
  const [productInvoice, setProductInvoice] = useState<any>({});
  const [selectedItems, setSelectedItems] = useState<any[]>([]);
  const [updatedQuantities, setUpdatedQuantities] = useState<any>({});
  const [selectAll, setSelectAll] = useState(false);
  const [total, setTotal] = useState(0);
  const [date, setDate] = useState("");
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });

  const columns: ColumnsType<DataType> = [
    {
      title: "S.No",
      dataIndex: "sno",
      key: "sno",
      width: 60,

      render: (text, object: any, index) => {
        return (
          <div style={{ width: "40px" }}>
            {object?.items.length > 0 ? index + 1 : null}
          </div>
        );
      },
      responsive: ["xs", "xl", "md"],
    },
    {
      title: "Created at",
      dataIndex: "created_at",
      key: "created_at",
      responsive: ["xs", "xl", "md"],
      sorter: (a: any, b: any) =>
        moment(a.created_at).format("DD-MM-YYYY") &&
        moment(a.created_at).format("DD-MM-YYYY") >
          moment(b.created_at).format("DD-MM-YYYY") &&
        moment(b.created_at).format("DD-MM-YYYY")
          ? 1
          : -1,
      render: (text, object: any, index) => {
        return object?.items.length > 0
          ? moment(object?.created_at).format("DD-MM-YYYY")
          : null;
      },
    },

    {
      title: "PO code",
      dataIndex: "purchase_order",
      key: "purchase_order",
      responsive: ["xs", "xl", "md"],
      sorter: (a: any, b: any) =>
        a?.purchase_order.localeCompare(b?.purchase_order),

      render: (text, object: any, index) => {
        return object?.items.length > 0 ? `${object.purchase_order}` : null;
      },
    },
    {
      title: "Quote ID",
      dataIndex: "quotation_code",
      key: "quotation_code",
      responsive: ["xs", "xl", "md"],
      sorter: (a: any, b: any) =>
        a?.quotation_code.localeCompare(b?.quotation_code),

      render: (text, object: any, index) => {
        return object?.items.length > 0 ? `${object.quotation_code}` : null;
      },
    },
    // {
    //     title: "Customer Name",
    //     dataIndex: "customerName",
    //     key: "customerName",
    //     responsive: ["xs", "xl", "md"],
    //     sorter: (a: any, b: any) =>
    //         a.customer_name.localeCompare(b?.customer_name),

    //     render: (text, object: any, index) => {
    //         return (
    //             object?.items.length>0?`${object.customer_name}`:null
    //         );
    //     },
    // },

    {
      title: "Items Count",
      dataIndex: "quantity",
      key: "quantity",
      responsive: ["xs", "xl", "md"],
      render: (text, object: any, index) => {
        return object?.items.length > 0 ? object?.items.length : null;
      },
    },

    {
      title: "Shipping Price",
      dataIndex: "CustomerLocation",
      key: "CustomerLocation",
      responsive: ["xs", "xl", "md"],

      render: (text, object: any, index) => {
        return object?.items.length > 0 ? `${object.shipping_charges}` : null;
      },
    },
    {
      title: "Estimated Shipping Date",
      dataIndex: "estimated_shipping_date",
      key: "estimated_shipping_date",
      responsive: ["xs", "xl", "md"],

      render: (text, object: any, index) => {
        return object?.items.length > 0
          ? object?.estimated_shipping_date
          : null;
      },
    },
    {
      title: "Action",
      key: "action",
      responsive: ["xl", "md", "xs"],
      render: (_, record: any) =>
        record?.items.length > 0 ? (
          <Space size="middle" className={styles.buttonsSelection}>
            <Button
              onClick={() => {
                downloadInvoice(record);
              }}
            >
              Download
            </Button>
            {record?.items?.some((item: any) => !item.sku) ? null : (
              <Popconfirm
                title={"Previous items in the cart will be deleted"}
                onConfirm={() => {
                  addTocart(record);
                }}
                okText="Yes"
                cancelText="Cancel"
              >
                <Button type="primary">{"Add to Cart"}</Button>
              </Popconfirm>
            )}
          </Space>
        ) : null,
    },
  ];

  const downloadInvoice = (order: any) => {
    axios
      .get(`${baseUrl}/api/customer/purchase-order/download/${order?.id}`, {
        responseType: "blob",
      })
      .then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");

        link.href = url;
        link.setAttribute("download", `${order?.purchase_order}.pdf`); //or any other extension
        document.body.appendChild(link);
        link.click();
      })
      .catch((error) => {});
  };

  const addTocart = (order: any) => {
    const pin = localStorage.getItem("PinCode");
    if (selectedItems.length > 0) {
      const items: any = [];

      selectedItems.map((item: any) => {
        const data = {
          [item?.rfq_item_id]: item?.quantity,
        };
        items.push(data);
      });
      const mergedObject: any = {};

      // Iterate through the array and merge key-value pairs into the mergedObject
      items.forEach((obj: any) => {
        const key = Object.keys(obj)[0]; // Get the key of the current object
        const value = obj[key]; // Get the value of the current object
        mergedObject[key] = updatedQuantities[key] || value; // Add the key-value pair to the mergedObject
      });

      const params = {
        customer_lat:
          currentAddress?.latitude == null
            ? latitude
            : currentAddress?.latitude,
        customer_lang:
          currentAddress?.latitude == null
            ? longitude
            : currentAddress?.latitude,
        customer_pincode: pin,
        items: mergedObject,
      };
      CommonAPI.postRequestWithToken(
        `${baseUrl}/api/customer/add-to-cart/${selectedItems?.[0]?.po_id}?token=true`,
        params,
        loginRes?.token
      ).then((res) => {
        // console.log(res,"res");
        if (res?.data?.warnings?.length == 0) {
          const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
          CartApi.cartFetch(tokenData).then((cartRes: any) => {
            if (cartRes.data !== null) {
              notification.success({ message: res?.data?.message });
              setProductInvoice(cartRes.data);
              setCartItems(cartRes.data);
              router.push("/cart");
            }
          });
        } else {
          notification.error({ message: res?.data?.warnings?.[0] });
        }
      });
    } else {
      const params = {
        customer_lat:
          currentAddress?.latitude == null
            ? latitude
            : currentAddress?.latitude,
        customer_lang:
          currentAddress?.latitude == null
            ? longitude
            : currentAddress?.latitude,
        customer_pincode: pin,
        items: updatedQuantities,
      };
      CommonAPI.postRequestWithToken(
        `${baseUrl}/api/customer/add-to-cart/${order?.id}?token=true`,
        params,
        loginRes?.token
      ).then((res) => {
        // console.log(res,"res");
        if (res?.data?.warnings?.length == 0) {
          const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
          CartApi.cartFetch(tokenData).then((cartRes: any) => {
            if (cartRes.data !== null) {
              notification.success({ message: res?.data?.message });
              setProductInvoice(cartRes.data);
              setCartItems(cartRes.data);
              router.push("/cart");
            }
          });
        } else {
          notification.error({ message: res?.data?.warnings?.[0] });
        }
      });
    }
  };

  const addItmsTocart = () => {
    const pin = localStorage.getItem("PinCode");
    const items: any = [];

    selectedItems.map((item: any) => {
      const data = {
        [item?.rfq_item_id]: item?.quantity,
      };
      items.push(data);
    });
    const mergedObject: any = {};

    // Iterate through the array and merge key-value pairs into the mergedObject
    items.forEach((obj: any) => {
      const key = Object.keys(obj)[0]; // Get the key of the current object
      const value = obj[key]; // Get the value of the current object
      mergedObject[key] = updatedQuantities[key] || value; // Add the key-value pair to the mergedObject
    });

    const params = {
      customer_lat:
        currentAddress?.latitude == null ? latitude : currentAddress?.latitude,
      customer_lang:
        currentAddress?.latitude == null ? longitude : currentAddress?.latitude,
      customer_pincode: pin,
      items: mergedObject,
    };
    CommonAPI.postRequestWithToken(
      `${baseUrl}/api/customer/add-to-cart/${selectedItems?.[0]?.po_id}?token=true`,
      params,
      loginRes?.token
    ).then((res) => {
      // console.log(res,"res");
      if (res?.data?.warnings?.length == 0) {
        const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
        CartApi.cartFetch(tokenData).then((cartRes: any) => {
          if (cartRes.data !== null) {
            notification.success({ message: res?.data?.message });
            setProductInvoice(cartRes.data);
            setCartItems(cartRes.data);
            router.push("/cart");
          }
        });
      } else {
        notification.error({ message: res?.data?.warnings?.[0] });
      }
    });
  };

  useEffect(() => {
    setLoading(true);
    const pin = localStorage.getItem("PinCode");
    const val: any = localStorage.getItem("loginDetails");
    const details: any = JSON.parse(val);
    setLoginRes(details);
    getList(
      tableParams?.pagination?.current,
      tableParams?.pagination?.pageSize,
      value,
      date
    );
    CommonAPI.getRequestWithToken(
      `${baseUrl}/api/customer-pincodes/get-data?token=true&customer_id=${details?.data?.id}`,
      details?.token
    ).then((Selectres) => {
      setCurrentAddress(Selectres?.data?.data);
    });
    if (pin !== null) {
      Geocode.setApiKey(APIKEY);
      Geocode.enableDebug();
      Geocode.fromAddress(pin).then(({ results }) => {
        const { lat, lng } = results[0].geometry.location;
        setLatitude(lat);
        setLongitude(lng);
      });
    }
  }, []);

  const getList = (page: any, limit: any, search: any,date:any) => {
    const val: any = localStorage.getItem("loginDetails");
    const details: any = JSON.parse(val);
    setLoginRes(details);
    CommonAPI.getRequestWithToken(
      `${baseUrl}/api/customer/purchase-orders?token=true&sort=desc&page=${page}&limit=${limit}&search=${search}&date=${date}`,
      details?.token
    ).then((res) => {
      setQuoteList(res?.data?.list);
      setNewQuotation(res?.data?.list);
      setTotal(res?.data?.total);
      setLoading(false);
    });
  };

  const poConvert = (order: any) => {
    CommonAPI.getRequestWithToken(
      `${baseUrl}/api/customer/convert-to-po/${order?.id}?token=true`,
      loginRes?.token
    ).then((res) => {
      console.log(res, "res");
      notification.success({ message: res?.data?.message });
      // setQuoteList(res?.data?.list)
    });
  };

  const onChange: TableProps<DataType>["onChange"] = (
    pagination: TablePaginationConfig,
    filters,
    sorter,
    extra
  ) => {
    getList(pagination?.current, pagination?.pageSize, value,date);
    setTableParams({
      pagination,
      ...sorter,
    });

    // `dataSource` is useless since `pageSize` changed
    if (pagination.pageSize !== tableParams.pagination?.pageSize) {
      setQuoteList([]);
    }
    setSorter(sorter);
  };

  const handleItemSelect = (itemId: any, poId: any) => {
    if (selectedItems.length != 0) {
      if (selectedItems.find((itm: any) => itm.po_id == poId)) {
        if (
          selectedItems.some((item: any) => {
            // Check if the object in selectedItems has the same properties and values as rfqToCheck
            return Object.keys(itemId).every(
              (key: any) => item[key] === itemId[key]
            );
          })
        ) {
          // If the item is already selected, remove it from the selectedItems array
          setSelectedItems(
            selectedItems.filter((id: any) => id.id != itemId.id)
          );
        } else {
          // If the item is not selected, add it to the selectedItems array
          setSelectedItems([...selectedItems, itemId]);
        }
      } else {
        setSelectedItems([]);
      }
    } else {
      setSelectedItems([itemId]);
    }
  };

  const handleItemQuantity = (rfq: any, event: any) => {
    setUpdatedQuantities({
      ...updatedQuantities,
      ...{
        [rfq.rfq_item_id]: event?.target?.value,
      },
    });
  };

  const handleSelectAll = (record: any) => {
    if (selectedItems.length > 0) {
      if (selectedItems?.[0]?.po_id != record.id) {
        setSelectedItems([]);
        setTimeout(() => {
          setSelectedItems(
            record.items.map((rfq: any) => ({ ...rfq, po_id: record.id }))
          );
        }, 10);
      } else {
        setSelectedItems([]);
      }
    } else {
      // If not selected, select all items
      setSelectedItems(
        record.items.map((rfq: any) => ({ ...rfq, po_id: record.id }))
      );
    }
  };

  const searchFun = (search: any) => {
    getList(
      tableParams?.pagination?.current,
      tableParams?.pagination?.pageSize,
      search,
      date
    );
  };

  const onChangeCalendar: DatePickerProps["onChange"] = async (
    date,
    dateString
  ) => {
    console.log(date, moment(dateString).format("YYYY-MM-DD"));
    setDate(dateString);
    getList(
        tableParams?.pagination?.current,
        tableParams?.pagination?.pageSize,
        value,
        dateString
      );
  };

  return (
    <>
      <Head>
        <title>{title}</title>
        <meta name="description" content={title} />
      </Head>
      <div className={styles.container}>
        <h1 className={styles.title}>Purchase Order</h1>
        <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"}
                  onChange={(e: any) => {
                    setValue(e.target.value);
                    searchFun(e.target.value);
                    return;
                    if (e.target.value === "") {
                      setQuoteList(newQuotation);
                      setValue("");
                    } else if (
                      e?.nativeEvent?.inputType == "deleteContentBackward"
                    ) {
                      const currValue = e.target.value.toLowerCase();
                      setValue(currValue);
                      const removeFilter = newQuotation;
                      const filteredData = removeFilter.filter((entry: any) => {
                        const name = entry?.customer_name.toLowerCase();
                        return name.includes(currValue);
                      });
                      setQuoteList(filteredData);
                    } else {
                      const currValue = e.target.value.toLowerCase();
                      setValue(currValue);
                      const filteredData = quoteList.filter((entry: any) => {
                        const name = entry?.customer_name || entry?.rfq_code;
                        const final_name = name.toLowerCase();
                        return final_name.includes(currValue);
                      });
                      setQuoteList(filteredData);
                    }
                  }}
                />
              </div>
              <div className={cx("ant-col ant-col-sm-24 ant-col-xl-8")}>
                <DatePicker onChange={onChangeCalendar} />
              </div>
            </div>
          </div>
          <div className={cx("ant-col ant-col-sm-24 ant-col-xl-8")}>
            <Popconfirm
              title={"Previous items in the cart will be deleted"}
              onConfirm={addItmsTocart}
              okText="Yes"
              cancelText="Cancel"
            >
              {selectedItems.length == 0 ? null : (
                <Button type="primary">{"Add to Cart"}</Button>
              )}
            </Popconfirm>
          </div>
        </div>
        {loading ? (
          <Skeleton />
        ) : (
          <Table
            columns={columns}
            dataSource={quoteList}
            className={styles.tablePlus}
            onChange={onChange}
            pagination={{
              ...tableParams.pagination,
              total: total,
            }}
            scroll={{ x: isMobile ? "100%" : 1400 }}
            expandable={{
              expandedRowRender: (record: any, idx: number) =>
                record?.items.length > 0 ? (
                  <div key={idx}>
                    <div className={cx("flex", styles.subTableAlign)}>
                      <table>
                        <tr className={styles.tableRow}>
                          <th>
                            {record?.items?.every((rfq: any) => rfq.sku) ? (
                              <input
                                type="checkbox"
                                checked={
                                  record?.items.length ==selectedItems.length && selectedItems?.[0]?.po_id ==
                                  record?.items?.[0]?.po_id
                                    ? true
                                    : false
                                }
                                onChange={() => handleSelectAll(record)}
                              />
                            ) : null}
                          </th>
                          {/* <th style={{ padding: "0.5rem", width: isMobile ? "100%" : "2rem" }}>Id</th> */}

                          <th style={{}}>Item Name</th>
                          <th style={{}}>SKU</th>

                          <th style={{}}>Quantity</th>
                          <th style={{}}>Price Demand</th>
                          <th style={{}}>Purchase Status</th>
                          <th style={{}}>Final Price</th>
                          {/* <th style={{ width: "180px" }}>Price</th> */}
                        </tr>

                        {record?.items?.map((rfq: any, key: number) => {
                          const rfqToCheck = { ...rfq, po_id: record.id };

                          return (
                            <tr key={key} className={styles.tableRow1}>
                              <td>
                                {!rfq.sku ? null : (
                                  <input
                                    type="checkbox"
                                    checked={selectedItems.some((item) => {
                                      // Check if the object in selectedItems has the same properties and values as rfqToCheck
                                      return Object.keys(rfqToCheck).every(
                                        (key: any) =>
                                          item[key] === rfqToCheck[key]
                                      );
                                    })} // Check if the item is selected
                                    onChange={() =>
                                      handleItemSelect(
                                        { ...rfq, po_id: record.id },
                                        record.id
                                      )
                                    } // Handle selection change
                                  />
                                )}
                              </td>
                              {/* <td style={{ textAlign: "center", padding: "0.5rem", width: isMobile ? "100%" : "2rem" }}>{isMobile ? <span className={styles.label}>Id : </span> : null}{rfq?.id}</td> */}
                              <td style={{}}>
                                {isMobile ? (
                                  <span className={styles.label}>
                                    Product Name :{" "}
                                  </span>
                                ) : null}
                                {rfq?.name}
                              </td>
                              <td style={{}}>
                                {isMobile ? (
                                  <span className={styles.label}>SKU : </span>
                                ) : null}
                                {rfq?.sku}
                              </td>
                              <td style={{}}>
                                {isMobile ? (
                                  <span className={styles.label}>
                                    Quantity :{" "}
                                  </span>
                                ) : null}
                                <Input
                                  style={{ width: 100 }}
                                  placeholder="Product Quantity"
                                  value={
                                    updatedQuantities[rfq.rfq_item_id] ||
                                    rfq?.quantity
                                  }
                                  onChange={(event) =>
                                    handleItemQuantity(rfq, event)
                                  }
                                />
                              </td>
                              <td style={{}}>
                                {isMobile ? (
                                  <span className={styles.label}>
                                    Price Demand :{" "}
                                  </span>
                                ) : null}{" "}
                                {rfq?.price_demanded}
                              </td>
                              <td style={{ textAlign: "center" }}>
                                {isMobile ? (
                                  <span className={styles.label}>
                                    Purchase status :{" "}
                                  </span>
                                ) : null}
                                {/* <DeleteOutlined style={{ color: "#f00", fontSize: "20px", marginLeft: "10px" }} /> */}
                              </td>
                              <td style={{ textAlign: "center" }}>
                                {isMobile ? (
                                  <span className={styles.label}>
                                    Final Price :{" "}
                                  </span>
                                ) : null}
                                {rfq?.customer_price}
                                {/* <DeleteOutlined style={{ color: "#f00", fontSize: "20px", marginLeft: "10px" }} /> */}
                              </td>
                            </tr>
                          );
                        })}
                      </table>
                    </div>
                  </div>
                ) : null,
              expandIcon: ({ expanded, onExpand, record }) =>
                record?.items.length > 0 ? (
                  expanded ? (
                    <MinusCircleTwoTone
                      onClick={(e) => onExpand(record, e)}
                      style={{ color: "#291c61" }}
                    />
                  ) : (
                    <PlusCircleTwoTone
                      onClick={(e) => onExpand(record, e)}
                      style={{ color: "#f00" }}
                    />
                  )
                ) : null,
            }}
            rowKey={(record: any) => {
              return record?.id;
            }}
          />
        )}
      </div>
    </>
  );
};

export default PurchaseOrder;
