import { FC, useEffect, useState } from "react";
import styles from "./rfqQuotation.module.scss";
import * as CommonAPI from "../../../pages/api/common";
import { baseUrl, s3BucketUrl } from "../../../constants/urls";
import {
  Button,
  Input,
  Modal,
  notification,
  Select,
  Skeleton,
  Space,
  Spin,
  Table,
} from "antd";
import { useMediaQuery } from "react-responsive";
import {
  SearchOutlined,
  FilterFilled,
  DeleteOutlined,
  DownloadOutlined,
  EyeOutlined,
  MinusCircleTwoTone,
  PlusCircleTwoTone,
  SwapOutlined,
  LoadingOutlined,
} from "@ant-design/icons";
import cx from "classnames";

import type {
  ColumnsType,
  TableProps,
  TablePaginationConfig,
} from "antd/es/table";
import type { FilterValue, SorterResult } from "antd/es/table/interface";
import moment from "moment";
import { capitalizeWords } from "../../../constants/commonFunction";
import axios from "axios";
import { useRouter } from "next/router";
import { isArray } from "lodash";
const antIcon = <LoadingOutlined style={{ fontSize: "26px" }} spin />;
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 getRandomuserParams = (params: TableParams) => ({
  results: params.pagination?.pageSize,
  page: params.pagination?.current,
  ...params,
});

const RFQQuotation: FC<any> = () => {
  const [loginRes, setLoginRes] = useState<any>({});
  const [quoteList, setQuoteList] = useState([]);
  const [newQuotation, setNewQuotation] = useState([]);
  const [value, setValue] = useState("");
  const [termsConditions, setTermsConditions] = useState("");
  const [rejectReason, setRejectReason] = useState("");
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [record, setRecord] = useState<any>({});
  const isMobile = useMediaQuery({ maxWidth: 767.68 });
  const [loading, setLoading] = useState(false);
  const [isRejectModalOpen, setIsRejectModalOpen] = useState(false);
  const [sorter, setSorter] = useState<any>({});
  const [loadingSpin, setLoadingSpin] = useState(false);
  const [selectedItems, setSelectedItems] = useState<any[]>([]);
  const [selectAll, setSelectAll] = useState(false);
  const [isItemsModalOpen, setIsItemsModalOpen] = useState(false);
  const [total, setTotal] = useState(0);
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });
  const [sortOrder, setSortOrder] = useState("desc");
  const router = useRouter();
  const columns: ColumnsType<DataType> = [
    {
      title: "S.No",
      dataIndex: "sno",
      key: "sno",
      width: 80,
      render: (text, object: any, index) => {
        return object?.items.length > 0 ? index + 1 : null;
      },
      responsive: ["xs", "xl", "md"],
    },
    {
      title: "Created At",
      dataIndex: "created_at",
      key: "created_at",
      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;
      },
      responsive: ["xs", "xl", "md"],
    },
    {
      title: "Quotation Code",
      dataIndex: "qid",
      key: "qid",
      render: (text, object: any, index) => {
        return object?.items.length > 0 ? object?.quotation_code : null;
      },
      responsive: ["xs", "xl", "md"],
    },
    {
      title: "RFQ ID",
      dataIndex: "rid",
      key: "rid",
      render: (text, object: any, index) => {
        return object?.items.length > 0 ? object?.rfq_code : null;
      },
      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?.items.length > 0 ? `${object.customer_name}` : null
    //         );
    //     },
    // },

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

      render: (text, object: any, index) => {
        return object?.items.length > 0 ? (
          <>
          <div
            dangerouslySetInnerHTML={{ __html: `${object.terms_conditions}` }}
          >
          </div>
          {object.comment!=""?<div><b>Reject Reason : </b>{object.comment}</div>:null}
          </>
        ) : 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: "Total Price",
      dataIndex: "total_amount",
      key: "total_amount",
      responsive: ["xs", "xl", "md"],

      sorter: (a: any, b: any) => a.total_amount.localeCompare(b?.total_amount),
      render: (text, object: any, index) => {
        return object?.items.length > 0 ? `${object.total_amount}` : null;
      },
    },
    {
      title: "Estimated Shipping Date",
      dataIndex: "createdat",
      key: "createdat",
      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"],
    //     render: (_, record: any) => (
    //         record?.items.length>0?<Space size="middle" className={styles.buttonsSelection}>
    //             <Button onClick={()=>{poConvert(record)}} >Convert to PO</Button>
    //             <Button onClick={()=>{downloadInvoice(record)}}>Download</Button>
    //             {/* <EyeOutlined style={{ color: "#291c62", fontSize: "24px" }} */}
    //              {/* onClick={()=>{select_rfq(record)}} */}
    //             {/* />
    //             <DeleteOutlined style={{ color: "#f00", fontSize: "20px" }} */}
    //                {/* onClick={()=>{deleteRfq(record)}} */}
    //             {/* /> */}
    //             {/* <Button type="primary" ghost className={styles.buttonsCart}>
    //         View invoice
    //       </Button> */}
    //         </Space>:null
    //     ),
    // },
    {
      title: "Status",
      key: "status",
      responsive: ["xl", "md", "xs"],
      render: (_, record: any) =>
        record?.items.length > 0 ? (
          <Space
            size="middle"
            className={cx(styles.buttonsSelection, styles.statusVale)}
          >
            <Select
              className={styles.statusVale}
              style={{width:"110px"}}
              placeholder="Status"
              options={[
                { value: "hold", label: "Hold" },
                { value: "rejected", label: "Rejected" },
                { value: "approved", label: "Approved" },
              ]}
              value={capitalizeWords(record?.status)}
              onChange={(e) => {
                statusUpdate(record, e);
              }}
            />
          </Space>
        ) : null,
    },
    {
      title: "Action",
      key: "action",
      responsive: ["xl", "md", "xs"],
      render: (_, record: any) =>
        record?.items.length > 0 ? (
          <Space size="middle" className={styles.buttonsSelection}>
            {record?.status == "approved" ? (
              <Button
                type="primary"
                ghost
                style={{marginLeft:"20px"}}
                className={styles.buttonsCart}
                onClick={() => {
                  showModal(record);
                }}
              >
                {" "}
                Convert TO PO{" "}
              </Button>
            ) : null}
            <Button
              type="primary"
              ghost
              style={{marginLeft:"20px"}}
              className={styles.buttonsCart}
              onClick={() => {
                downloadInvoice(record);
              }}
            >
              Download
            </Button>
            {/* <DownloadOutlined style={{ color: "#291c62", fontSize: "24px" }} onClick={() => { downloadInvoice(record) }} /> */}
            {/* <EyeOutlined style={{ color: "#291c62", fontSize: "24px" }} */}
            {/* onClick={()=>{select_rfq(record)}} */}
            {/* />
                    <DeleteOutlined style={{ color: "#f00", fontSize: "20px" }} */}
            {/* onClick={()=>{deleteRfq(record)}} */}
            {/* /> */}
            {/* <Button type="primary" ghost className={styles.buttonsCart}>
                View invoice
              </Button> */}
          </Space>
        ) : null,
    },
  ];

  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 cancel = () => {
    // setEditingKey('');
  };

  useEffect(() => {
    setLoading(true);
    const val: any = localStorage.getItem("loginDetails");
    const details: any = JSON.parse(val);
    setLoginRes(details);
    const sortOrder =
      sorter?.order === "ascend"
        ? "asc"
        : sorter?.order === "descend"
        ? "desc"
        : "desc";
    const sortColumn = sorter?.columnKey;
    const optionalParam = sortColumn
      ? `&sort=${sortOrder}&sort_column=${sortColumn}`
      : `&sort=${sortOrder}`;
      list(tableParams?.pagination?.current,tableParams?.pagination?.pageSize);
  }, [sorter]);


  const list =(page:any,limit:any)=>{
    const val: any = localStorage.getItem("loginDetails");
    const details: any = JSON.parse(val);
    CommonAPI.getRequestWithToken(
      `${baseUrl}/api/customer/quotations?token=true&page=${page}&limit=${limit}`,
      details?.token
    ).then((res) => {
      setLoading(false);
      if (isArray(res?.data?.list)) {
        setQuoteList(res?.data?.list);
        setNewQuotation(res?.data?.list);
        setTotal(res?.data?.total)
        
      }
    });
  }
  const statusUpdate = (data: any, status: any) => {
    // console.log(status, "status");

    if (status == "rejected") {
      showRejectModal(data);
    } else {
      setLoadingSpin(true);
      setQuoteList([]);
      setNewQuotation([]);
      CommonAPI.patchRequestWithToken(
        `${baseUrl}/api/customer/change-quotation-status/${data?.id}/${status}?token=true`,
        loginRes?.token
      ).then((res) => {
        CommonAPI.getRequestWithToken(
          `${baseUrl}/api/customer/quotations?token=true&search=${""}&sort=desc`,
          loginRes?.token
        ).then((res) => {
          setLoadingSpin(false);
          setQuoteList(res?.data?.list);
          setNewQuotation(res?.data?.list);
        });
      });
    }
  };

  const poConvert = (order: any) => {
    setLoadingSpin(true);
    const idString = selectedItems?.map((item) => `${item.id}`).join(",");
    const rfqItemString = selectedItems
      ?.map((item) => `${item.rfq_item_id}`)
      .join(",");
    const po_id =
      selectedItems.length == 0 ? order?.id : selectedItems?.[0]?.po_id;
    CommonAPI.getRequestWithToken(
      `${baseUrl}/api/customer/convert-to-po/${po_id}?token=true?terms_conditions=${termsConditions}&quotation_item_ids=${idString}&rfq_items_id=${rfqItemString}`,
      loginRes?.token
    ).then((res) => {
      notification.success({ message: res?.data?.message });
      setLoadingSpin(false);
      router.push({
        pathname: `/customerDashboard/customerDashboard`,
        query: { val: "Purchase Order" },
      });
    });
    setRecord({});
    setTermsConditions("");
  };

  const rejectRfq = (order: any) => {
    setLoadingSpin(true);
    console.log(order, "order");

    CommonAPI.patchRequestWithDataToken(
      `${baseUrl}/api/customer/change-quotation-status/${order?.id}/reject?token=true`,
      loginRes?.token,
      rejectReason
    ).then((res) => {
      CommonAPI.getRequestWithToken(
        `${baseUrl}/api/customer/quotations?token=true&search=${""}&sort=desc`,
        loginRes?.token
      ).then((res) => {
        setLoadingSpin(false);
        setQuoteList(res?.data?.list);
        setNewQuotation(res?.data?.list);
        setRecord({});
        setRejectReason("");
      });
    });
  };

  const Search = (search: any) => {
    CommonAPI.getRequestWithToken(
      `${baseUrl}/api/customer/quotations?token=true&search=${search}&sort=desc`,
      loginRes?.token
    ).then((res) => {
      // console.log(res, "res");
      setQuoteList(res?.data?.list);
      setNewQuotation(res?.data?.list);
    });
  };
  const downloadInvoice = (order: any) => {
    axios
      .get(`${baseUrl}/api/customer/quotation/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?.rfq_code}.pdf`); //or any other extension
        document.body.appendChild(link);
        link.click();
      })
      .catch((error) => {});
  };

  const showModal = (order: any) => {
    setRecord(order);
    setIsModalOpen(true);
  };

  const handleOk = () => {
    poConvert(record);
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    setTermsConditions("");
  };

  const showItmesModal = () => {
    setIsItemsModalOpen(true);
  };

  const handleItemsOk = () => {
    PoConvertItem();
    setIsItemsModalOpen(false);
  };

  const handleItemsCancel = () => {
    setIsItemsModalOpen(false);
    setTermsConditions("");
  };

  const showRejectModal = (order: any) => {
    setRecord(order);
    setIsRejectModalOpen(true);
  };

  const handleRejectOk = () => {
    if (rejectReason == "") {
      notification.warning({ message: "Please Enter Reason" });
    } else {
      rejectRfq(record);
      setIsRejectModalOpen(false);
    }
  };

  const handleRejectCancel = () => {
    setIsRejectModalOpen(false);
    setRejectReason("");
  };

  const onChange: TableProps<DataType>["onChange"] = (
    pagination: TablePaginationConfig,
    filters,
    sorter,
    extra
  ) => {
    list(pagination?.current,pagination?.pageSize);
    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 PoConvertItem = () => {
    const idString = selectedItems.map((item) => `${item.id}`).join(",");
    const rfqItemString = selectedItems
      .map((item) => `${item.rfq_item_id}`)
      .join(",");

    CommonAPI.getRequestWithToken(
      `${baseUrl}/api/customer/convert-to-po/${selectedItems?.[0]?.po_id}?token=true&terms_conditions=${termsConditions}&quotation_item_ids=${idString}&rfq_items_id=${rfqItemString}`,
      loginRes?.token
    ).then((res) => {
      notification.success({ message: res?.data?.message });
      setLoadingSpin(false);
      router.push({
        pathname: `/customerDashboard/customerDashboard`,
        query: { val: "Purchase Order" },
      });
    });
  };

  return (
    <>
      <div className={styles.container}>
        <h1 className={styles.title}>RFQ Quotations</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);
                    Search(e.target.value);
                    // 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.toLowerCase()
                    //         return name.includes(currValue);
                    //     });
                    //     setQuoteList(filteredData);
                    // }
                  }}
                />
              </div>
            </div>
          </div>
          <div className={cx("ant-col ant-col-sm-24 ant-col-xl-8")}>
            {selectedItems.length == 0 ? null : (
              <Button
                type="primary"
                ghost
                className={styles.buttonsCart}
                onClick={() => {
                  showItmesModal();
                }}
              >
                {" "}
                Convert TO PO{" "}
              </Button>
            )}
          </div>
        </div>
        {loading ? (
          <Skeleton />
        ) : (
          <Table
            columns={columns}
            dataSource={quoteList}
            className={styles.tablePlus}
            onChange={onChange}
            pagination={{
              ...tableParams.pagination,
              total: total,
            }}
            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.status == "approved" && !record?.items?.every((rfq: any) => rfq.order_type)? (
                              <input
                                type="checkbox"
                                checked={record?.items.length== selectedItems.length && selectedItems.length!=0&&selectedItems?.[0]?.po_id==record?.items?.[0]?.quotation_id?true:false}
                                onChange={() => handleSelectAll(record)}
                              />
                            ) : null}
                          </th>
                          {/* <th style={{ padding: "0.5rem", width: isMobile ? "100%" : "2rem" }}>Id</th> */}
                          <th>Item Name</th>
                          <th>SKU</th>

                          <th>Quantity</th>
                          <th>Price Expected</th>
                          <th>Final Price</th>
                          <th>PO Status</th>
                        </tr>

                        {record?.items?.map((rfq: any, key: number) => {
                          const rfqToCheck = { ...rfq, po_id: record.id };
                          return (
                            <tr key={key} className={styles.tableRow1}>
                              <td>
                                {record.status == "approved" && rfq?.order_type!="po" ? (
                                  <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
                                  />
                                ) : null}
                              </td>
                              {/* <td style={{ textAlign: "center", padding: "0.5rem", width: isMobile ? "100%" : "2rem" }}>{isMobile ? <span className={styles.label}>Id : </span> : null}{rfq?.id}</td> */}
                              <td>
                                {isMobile ? (
                                  <span className={styles.label}>
                                    Product Name :{" "}
                                  </span>
                                ) : null}
                                {rfq?.name}
                              </td>
                              <td>
                                {isMobile ? (
                                  <span className={styles.label}>SKU : </span>
                                ) : null}
                                {rfq?.sku}
                              </td>
                              <td>
                                {isMobile ? (
                                  <span className={styles.label}>
                                    Quantity :{" "}
                                  </span>
                                ) : null}
                                {rfq?.quantity}
                              </td>
                              <td>
                                {isMobile ? (
                                  <span className={styles.label}>
                                    Price Expected :{" "}
                                  </span>
                                ) : null}{" "}
                                {rfq?.price_demanded}
                              </td>
                              <td>
                                {isMobile ? (
                                  <span className={styles.label}>
                                    Final Price :{" "}
                                  </span>
                                ) : null}
                                {rfq?.customer_price}
                                {/* <DeleteOutlined style={{ color: "#f00", fontSize: "20px", marginLeft: "10px" }} /> */}
                              </td>
                              <td>
                                {isMobile ? (
                                  <span className={styles.label}>
                                    Po Status :{" "}
                                  </span>
                                ) : null}
                                {rfq?.order_type=="po"?"PO Converted":null}
                                {/* <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;
            }}
            scroll={{ x: 1400, y: 370 }}
          />
        )}
      </div>
      <Modal
        title="Additional Terms and Conditions"
        visible={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Input.TextArea
          value={termsConditions}
          placeholder="Additional Terms and Conditions"
          size={"middle"}
          onChange={(e: any) => {
            setTermsConditions(e.target.value);
          }}
        />
      </Modal>

      <Modal
        title="Additional Terms and Conditions"
        visible={isItemsModalOpen}
        onOk={handleItemsOk}
        onCancel={handleItemsCancel}
      >
        <Input.TextArea
          value={termsConditions}
          placeholder="Additional Terms and Conditions"
          size={"middle"}
          onChange={(e: any) => {
            setTermsConditions(e.target.value);
          }}
        />
      </Modal>
      <Modal
        title="Reject Reason"
        visible={isRejectModalOpen}
        onOk={handleRejectOk}
        onCancel={handleRejectCancel}
      >
        <Input.TextArea
          value={rejectReason}
          placeholder="Enter Reject Reason "
          size={"middle"}
          onChange={(e: any) => {
            setRejectReason(e.target.value);
          }}
        />
      </Modal>
      <Spin
        indicator={antIcon}
        spinning={loadingSpin}
        className={styles.loaderContainer}
      />
    </>
  );
};

export default RFQQuotation;
