import {
  Button,
  Input,
  notification,
  Select,
  Skeleton,
  Space,
  Table,
} from "antd";
import { FC, useEffect, useState } from "react";
import styles from "./rfqList.module.scss";
import cx from "classnames";
import {
  SearchOutlined,
  FilterFilled,
  DeleteOutlined,
  DownloadOutlined,
  EyeOutlined,
  MinusCircleTwoTone,
  PlusCircleTwoTone,
  EyeInvisibleOutlined,
  FundViewOutlined,
  EyeFilled,
} from "@ant-design/icons";

import type {
  ColumnsType,
  TableProps,
  TablePaginationConfig,
} from "antd/es/table";
import * as Invoice from "../../../pages/api/invoice";
import axios from "axios";
import moment from "moment";
import { baseUrl } from "../../../constants/urls";
import EditRfq from "./EditRfq";
import * as RFQAPI from "../../../pages/api/rfq";
import { useMediaQuery } from "react-responsive";
import { capitalizeWords } from "../../../constants/commonFunction";
import SellerPricingList from "../sellerPricing/SellerPricingList";
import { isEmpty } from "lodash";
import { useRouter } from "next/router";
import type { FilterValue, SorterResult } from "antd/es/table/interface";

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

interface TableParams {
  pagination?: TablePaginationConfig;
  sortField?: string;
  sortOrder?: string;
  filters?: Record<string, FilterValue>;
}
const RfqList: FC<any> = () => {
  const columns: ColumnsType<DataType> = [
    {
      title: "S.no",
      dataIndex: "index",
      key: "index",

      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 `${moment(object?.created_at).format("DD-MM-YYYY")}`;
      },
    },
    // {
    //   title: "Representative Name",
    //   dataIndex: "representative_name",
    //   key: "representative_name",
    //   render: (text, object: any, index) => {
    //     return object?.representative_name;
    //   },
    //   sorter: (a: any, b: any) =>
    //     a?.representative_name.localeCompare(b?.representative_name),
    //   responsive: ["xs", "xl", "md"],
    // },
    // {
    //   title: "Representative Phone Number",
    //   dataIndex: "representative_contact_number",
    //   key: "representative_contact_number",
    //   render: (text, object: any, index) => {
    //     return object?.representative_contact_number;
    //   },
    //   sorter: (a: any, b: any) =>
    //     a?.representative_contact_number.localeCompare(b?.representative_contact_number),
    //   responsive: ["xs", "xl", "md"],
    // },

    {
      title: "RFQID",
      dataIndex: "RFID",
      key: "RFID",
      render: (text, object: any, index) => {
        return object?.rfq_code;
      },

      responsive: ["xs", "xl", "md"],
    },
    // {
    //   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?.customer_name}`
    //     );
    //   },
    // },

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

      render: (text, object: any, index) => {
        return `${object?.comment}`;
      },
    },

    // {
    //   title: "Customer Location",
    //   dataIndex: "CustomerLocation",
    //   key: "CustomerLocation",
    //   responsive: ["xl", "md"],

    //   render: (text, object: any, index) => {
    //     return `${object?.customer_location}`;
    //   },
    // },

    {
      title: "Action",
      key: "action",
      responsive: ["xl", "md", "xs"],
      render: (_, record: any) => (
        <Space size="middle" className={styles.buttonsSelection}>
          {/* <FundViewOutlined   style={{ color: "#291c62" }} onClick={() => { select_rfq(record) }} /> */}

          {record?.seller_response_available ? (
            <Button
              type="primary"
              ghost
              onClick={() => {
                priceList(record);
              }}
              className="blink"
              style={{ background: "#14B16F", color: "#fff" }}
            >
              RFQ Response
            </Button>
          ) : null}
          <Button
            type="primary"
            onClick={() => {
              select_rfq(record);
            }}
          >
            View
          </Button>
          {record?.status == "Quotation Generated" ? null : (
            <DeleteOutlined
              style={{ color: "#f00", fontSize: "20px" }}
              onClick={() => {
                deleteRfq(record);
              }}
            />
          )}

          {/* <Button type="primary" ghost className={styles.buttonsCart}>
            View invoice
          </Button> */}
        </Space>
      ),
    },
  ];

  const [product, setProduct] = useState<DataType[]>([]);
  const [newProduct, setNewProduct] = useState<DataType[]>([]);
  const [removeProduct, setRemoveProduct] = useState<DataType[]>([]);
  const [loginRes, setLoginRes] = useState<any>({});
  const [value, setValue] = useState("");
  const [isBack, setBack] = useState(false);
  const [rfqData, setRfqData] = useState<any>({});
  const isMobile = useMediaQuery({ maxWidth: 767.68 });
  const [loading, setLoading] = useState(false);
  const [sorter, setSorter] = useState<any>({});
  const [sortOrder, setSortOrder] = useState("desc");
  const [sortColumn, setSortColumn] = useState("created_at");
  const [isSellerPrice, setIsSellerPrice] = useState(false);
  const router = useRouter();
  const [total, setTotal] = useState(0);
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 20,
    },
  });
  useEffect(() => {
    setLoading(true);
    const val: any = localStorage.getItem("loginDetails");
    const details: any = JSON.parse(val);
    // console.log(details, "details");

    setLoginRes(details);
    if (isEmpty(details)) {
      router.push("/#login");
    } else {
      list(
        details?.token,
        "",
        tableParams?.pagination?.current,
        tableParams?.pagination?.pageSize
      );
    }
  }, []);

  useEffect(() => {
    const val: any = localStorage.getItem("loginDetails");
    const details: any = JSON.parse(val);
    const sort =
      sorter?.order === "ascend"
        ? "asc"
        : sorter?.order === "descend"
        ? "desc"
        : "desc";
    setSortOrder(sort);

    setSortColumn(sorter?.columnKey || "");
    if (isEmpty(details)) {
      router.push("/#login");
    } else {
      list(
        details?.token,
        "",
        tableParams?.pagination?.current,
        tableParams?.pagination?.pageSize
      );
    }
  }, [sorter]);

  const list = async (token: any, search: any, page: any, limit: any) => {
    const _filert = {
      page: page,
      limit: limit,
      search: search,
      sort: sortOrder,
      sort_column: sortColumn,
    };
    await axios
      .get(Invoice.rfqListApi, {
        params: { ..._filert },
        headers: {
          Accept: "application/json",
          Authorization: `Bearer ` + token,
        },
      })
      .then((res) => {
        setLoading(false);
        const prod: any = [];

        setProduct(res?.data?.list);
        setNewProduct(res?.data?.list);
        setRemoveProduct(res?.data?.list);
        setTotal(res?.data?.total);
        return;
        res?.data?.data.map((product: any, idx: number) => {
          const prodObj = {
            key: idx,
            sno: idx + 1,
            id: product?.product?.id,
            customerName:
              product?.order_address?.first_name +
              product?.order_address?.last_name,
            purchaseDate: moment(product?.created_at).format("DD-MM-YYYY"),
            price: product?.formated_sub_total,
            quantity: product?.total_qty,
            amount: product?.formated_grand_total,
          };
          prod.push(prodObj);
        });
        setProduct(prod);
      });
  };

  const backOption = () => {
    setBack(false);
    setIsSellerPrice(false);
    setRfqData({});
    list(
      loginRes?.token,
      "",
      tableParams?.pagination?.current,
      tableParams?.pagination?.pageSize
    );
  };

  const deleteRfq = (data: any) => {
    // console.log(data,"data")
    const params = {
      id: data?.id,
      token: loginRes?.token,
    };
    RFQAPI.deleteRfq(params).then((res) => {
      notification.success({ message: res?.message });
      list(
        loginRes?.token,
        "",
        tableParams?.pagination?.current,
        tableParams?.pagination?.pageSize
      );
      // console.log(res,"res")
    });
  };

  const deleteItemsRfq = (data: any) => {
    // console.log(data,"data")
    const params = {
      id: data?.id,
      token: loginRes?.token,
    };
    RFQAPI.deleteItemRfq(params).then((res) => {
      notification.success({ message: res?.message });
      list(
        loginRes?.token,
        "",
        tableParams?.pagination?.current,
        tableParams?.pagination?.pageSize
      );
      // console.log(res,"res")
    });
  };
  const select_rfq = (data: any) => {
    setRfqData(data);
    setTimeout(() => {
      setBack(true);
    }, 100);
  };

  const Search = (search: any) => {
    list(
      loginRes?.token,
      search,
      tableParams?.pagination?.current,
      tableParams?.pagination?.pageSize
    );
  };

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

    // `dataSource` is useless since `pageSize` changed
    if (pagination.pageSize !== tableParams.pagination?.pageSize) {
      setProduct([]);
    }
    setSorter(sorter);
  };
  const priceList = (data: any) => {
    setRfqData(data);
    setTimeout(() => {
      setIsSellerPrice(true);
    }, 100);
  };
  const dataSource = product.map((item, index) => ({
    ...item,
    index: index + 1, // Starting index from 1
  }));

  // const handleSearch = (e) => {
  //   const { value } = e.target;
  //   setSearchText(value);

  //   const filteredData = dataSource.filter((item) =>
  //     Object.keys(item).some(
  //       (key) =>
  //         item[key]
  //           .toString()
  //           .toLowerCase()
  //           .indexOf(value.toLowerCase()) !== -1
  //     )
  //   );

  //   setData(filteredData);
  // };

  return (
    <>
      {!isBack && !isSellerPrice ? (
        <div className={styles.container}>
          <h1 className={styles.title}>RFQ List</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) => {
                      // Search(e.target.value);
                      setValue(e.target.value);
                      if (e.target.value === "") {
                        setProduct(newProduct);
                        setValue("");
                      } else if (
                        e?.nativeEvent?.inputType == "deleteContentBackward"
                      ) {
                        const currValue = e.target.value.toLowerCase();
                        setValue(currValue);
                        const removeFilter = removeProduct;
                        const filteredData = removeFilter.filter(
                          (entry: any) => {
                            const name = entry?.rfq_code.toLowerCase();
                            return name.includes(currValue);
                          }
                        );
                        setProduct(filteredData);
                      } else {
                        const currValue = e.target.value.toLowerCase();
                        setValue(currValue);
                        const filteredData = product.filter((entry: any) => {
                          const name = entry?.rfq_code.toLowerCase();
                          return name.includes(currValue);
                        });
                        setProduct(filteredData);
                      }
                    }}
                  />
                </div>
              </div>
            </div>
            <div className={cx("ant-col ant-col-sm-24 ant-col-xl-8")} />
          </div>
          {loading ? (
            <Skeleton />
          ) : (
            <Table
              columns={columns}
              dataSource={dataSource}
              className={styles.tablePlus}
              onChange={onChange}
              pagination={{
                ...tableParams.pagination,
                total: total,
              }}
              scroll={{ x: isMobile ? "100%" : 1400 }}
              expandable={{
                expandedRowRender: (record: any, idx: number) => (
                  <div key={idx}>
                    <div className={cx("flex", styles.subTableAlign)}>
                      <table>
                        <tr className={styles.tableRow}>
                          <th
                            style={{
                              padding: "0.5rem",
                              width: isMobile ? "100%" : "2rem",
                            }}
                          >
                            Id
                          </th>
                          <th style={{}}>Item Name</th>
                          <th>Specification</th>
                          <th>Seller</th>
                          <th>Brand</th>
                          <th>Quantity</th>
                          <th>Delivery Date</th>
                          {/* <th style={{ width: "180px" }}>Price</th> */}
                        </tr>

                        {record?.items?.map((rfq: any, key: number) => {
                          return (
                            <tr key={key} className={styles.tableRow1}>
                              <td
                                style={{
                                  padding: "0.5rem",
                                  width: isMobile ? "100%" : "4rem",
                                  display: isMobile ? "none" : "block",
                                }}
                              >
                                {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}>
                                    Specification :{" "}
                                  </span>
                                ) : null}
                                {rfq?.specifications}
                              </td>
                              <td style={{}}>
                                {isMobile ? (
                                  <span className={styles.label}>
                                    Seller :{" "}
                                  </span>
                                ) : null}
                                {rfq?.seller_code}
                              </td>
                              <td style={{}}>
                                {isMobile ? (
                                  <span className={styles.label}>
                                    Brand Name :{" "}
                                  </span>
                                ) : null}
                                {capitalizeWords(rfq?.brand)}
                              </td>
                              <td style={{}}>
                                {isMobile ? (
                                  <span className={styles.label}>
                                    Quantity :{" "}
                                  </span>
                                ) : null}{" "}
                                {rfq?.quantity}
                              </td>
                              <td style={{}}>
                                {isMobile ? (
                                  <span className={styles.label}>
                                    Delivery Date :{" "}
                                  </span>
                                ) : null}
                                {rfq?.delivery_date}
                                <DeleteOutlined
                                  style={{
                                    color: "#f00 !important",
                                    fontSize: "20px",
                                    marginLeft: "10px",
                                  }}
                                  onClick={() => {
                                    deleteItemsRfq(rfq);
                                  }}
                                />
                              </td>
                            </tr>
                          );
                        })}
                      </table>
                    </div>
                  </div>
                ),
                expandIcon: ({ expanded, onExpand, record }) =>
                  expanded ? (
                    <MinusCircleTwoTone
                      onClick={(e) => onExpand(record, e)}
                      style={{ color: "#291c61" }}
                    />
                  ) : (
                    <PlusCircleTwoTone
                      onClick={(e) => onExpand(record, e)}
                      style={{ color: "#f00" }}
                    />
                  ),
              }}
              rowKey={(record: any) => {
                return record?.id;
              }}
            />
          )}
        </div>
      ) : isBack && !isSellerPrice ? (
        <EditRfq
          backOption={backOption}
          rfqData={rfqData}
          loginRes={loginRes}
        />
      ) : (
        <SellerPricingList
          backOption={backOption}
          rfqData={rfqData}
          loginRes={loginRes}
        />
      )}
    </>
  );
};

export default RfqList;
