import { Button, DatePicker, Input, Pagination, Select, Skeleton, Space, Table } from "antd";
import { FC, useEffect, useState } from "react";
import styles from "./newInvoiceList.module.scss";
import cx from "classnames";
import {
  SearchOutlined,
  FilterFilled,
  DeleteOutlined,
  DownloadOutlined,
  EyeOutlined,
} from "@ant-design/icons";
import type { ColumnsType } 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 { useRouter } from "next/router";
import type { DatePickerProps } from 'antd';

interface DataType {
  key: React.Key;
  sno: string;
  itemName: string;
  quantity: any;
  price: any;
}
const NewInvoiceList: FC<any> = () => {
  const columns: ColumnsType<DataType> = [
    {
      title: "S.No",
      dataIndex: "index",
      key: "sno",
      // render: (text, object, index) => {
      //   return index + 1;
      // },
      responsive: ["xs", "xl", "md"],
    },
    {
      title: "Seller Code",
      dataIndex: "manufacturer_label",
      key: "manufacturer_label",
      responsive: ["xl", "md"],
      sorter: (a: any, b: any) =>
        a?.items?.[0]?.additional?.seller_code?.localeCompare(b?.items?.[0]?.additional?.seller_code),

      render: (text, object: any, index) => {
        return (
          `${object?.items?.[0]?.additional?.seller_code}` 
        );
      },
    },
    {
      title: "Invoice Id",
      dataIndex: "invoice_id",
      key: "invoice_id",
      responsive: ["xl", "md"],
      sorter: (a: any, b: any) =>
        a.invoice_id.localeCompare(b.invoice_id),

      render: (text, object: any, index) => {
        return `${object.invoice_id}`;
      },
    },
    {
      title: "Created At",
      dataIndex: "purchaseDate",
      key: "purchaseDate",
      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: "Order Id",
      dataIndex: "increment_id",
      key: "increment_id",
      responsive: ["xs", "xl", "md"],
      //sorter: (a: any, b: any) => a.total_qty.localeCompare(b.total_qty),

      render: (text, object: any, index) => {
        return `${object.increment_id}`;
      },
    },
    // {
    //   title: "Amount",
    //   dataIndex: "amount",
    //   key: "amount",
    //   responsive: ["xs", "xl", "md"],
    //   sorter: (a: any, b: any) =>
    //     a.formated_grand_total.localeCompare(b.formated_grand_total),
    //   render: (text, object: any, index) => {
    //     return `${object.formated_grand_total}`;
    //   },
    // },

    {
      title: "Action",
      key: "action",
      responsive: ["xl", "md"],
      render: (_, record: any) => (
        <Space size="middle" className={styles.buttonsSelection}>
          <Button
            type="primary"
            className={styles.buttonsCart}
            onClick={() => {
              downloadInvoice(record);
            }}
          >
            Download Invoice
          </Button>
          <Button type="primary" ghost className={styles.buttonsCart} onClick={() => {
              isInvoiceView(record);
            }}>
            View Invoice
          </Button>
        </Space>
      ),
    },
    {
      title: "Action",
      key: "action",
      responsive: ["xs"],
      render: (_, record: any) => (
        <Space size="middle" className={styles.buttonsSelection}>
          <DownloadOutlined
            className={styles.buttonsCart}
            onClick={() => {
              downloadInvoice(record);
            }}
          />
          <EyeOutlined className={styles.buttonsCart} onClick={() => {
              isInvoiceView(record);
            }}/>
          {/* <Button type="primary" className={styles.buttonsCart}>
            Download Invoice
          </Button> */}
          {/*  */}
          {/* <Button type="primary" ghost className={styles.buttonsCart}>
            View invoice
          </Button> */}
        </Space>
      ),
    },
  ];
  const downloadInvoice = (order: any) => {
    axios
      .get(`${baseUrl}/api/customisation/invoices/${order?.id}/download`, {
        responseType: "blob",
      })
      .then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");

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

  const [product, setProduct] = useState<DataType[]>([]);
  const [newProduct, setNewProduct] = useState<DataType[]>([]);
  const [loginRes, setLoginRes] = useState<any>({});
  const [value, setValue] = useState("");
  const [pageSize, setPageSize] = useState(10);
  const [pageNumber, setPageNumber] = useState(1);
  const [totalData, setTotalData] = useState(0);
  const [isLoading,setIsLoading] = useState(false);
  const [date,setDate] = useState("");
  const router = useRouter();
  useEffect(() => {
    setIsLoading(true)
    const val: any = localStorage.getItem("loginDetails");
    const details: any = JSON.parse(val);
    

    setLoginRes(details);
    list(pageNumber,pageSize);
  }, []);

  const list = async (pageNumber: number, pageSize: number) => {
    const val: any = localStorage.getItem("loginDetails");
    const details = JSON.parse(val);
    const token = details?.token
    const _filert = {
      page: pageNumber,
      limit: pageSize,
    };
    await axios
      .get(`${baseUrl}/api/invoices-list?token=true`, {
        params: { ..._filert },
        headers: {
          Accept: "application/json",
          Authorization: `Bearer ` + token,
        },
      })
      .then((res) => {
        const prod: any = [];
        console.log(res,"res")
        setProduct(res?.data?.data);
        setNewProduct(res?.data?.data);
        setTotalData(res?.data?.meta?.total)
        setIsLoading(false)
        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 search =async(pageNumber: number, pageSize: number,search:any)=>{
    const val: any = localStorage.getItem("loginDetails");
    const details = JSON.parse(val);
    const token = details?.token
    const _filert = {
      page: pageNumber,
      limit: pageSize,
      search:search
    };
    await axios
      .get(`${baseUrl}/api/invoices-list?token=true`, {
        params: { ..._filert },
        headers: {
          Accept: "application/json",
          Authorization: `Bearer ` + token,
        },
      })
      .then((res:any) => {
        console.log(res,"res")
        const prod: any = [];
        console.log(res,"res")
        setProduct(res?.data?.data);
        setNewProduct(res?.data?.data);
        setTotalData(res?.data?.meta?.total)
      })
  }
  /* change page number function */
  const onPaginationChange = (newCurrentPage: number) => {
    list( newCurrentPage, pageSize);
    setPageNumber(newCurrentPage);
  };

  /* change page size function */
  const onPageSizeChange = (current: number, size: number) => {
    list(current, size);
    setPageSize(size);
  };

  const isInvoiceView = (order: any) => {
    console.log(order,"order")
    router.push(`/customer/account/invoice/view/${order.invoice_id}`);
  }

  const onChange: DatePickerProps['onChange'] = async(date, dateString) => {
    console.log(date, moment(dateString).format("YYYY-MM-DD"));
     setDate(dateString);
     const val: any = localStorage.getItem("loginDetails");
    const details = JSON.parse(val);
    const token = details?.token
    const _filert = {
      page: pageNumber,
      limit: pageSize,
      search:value,
      date:dateString
    };
    await axios
      .get(`${baseUrl}/api/invoices-list?token=true`, {
        params: { ..._filert },
        headers: {
          Accept: "application/json",
          Authorization: `Bearer ` + token,
        },
      })
      .then((res:any) => {
        console.log(res,"res")
        const prod: any = [];
        console.log(res,"res")
        setProduct(res?.data?.data);
        setNewProduct(res?.data?.data);
        setTotalData(res?.data?.meta?.total)
      })

  };

  const dataSource = product.map((item, index) => ({
    ...item,
    index: index + 1,  // Starting index from 1
  }));

  return (
    <>
      <div className={styles.container}>
        <h1 className={styles.title}>Invoices 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) => {
                    const currValue = e.target.value;

                      setValue(currValue);
                    search(pageNumber,pageSize,e.target.value);
                    return;
                    if (e.target.value === "") {
                      setProduct(newProduct);
                      setValue("");
                    } else {
                      const currValue = e.target.value;

                      setValue(currValue);
                      const filteredData = product.filter((entry: any) => {
                        const name =
                          entry.order_address?.first_name ||
                          entry.order_address?.last_name ||
                          entry.formated_sub_total ||
                          entry.formated_grand_total ||
                          moment(entry?.created_at).format("DD-MM-YYYY");
                        return name.includes(currValue);
                      });
                      setProduct(filteredData);
                    }
                  }}
                />
              </div>
              <div className={cx("ant-col ant-col-sm-24 ant-col-xl-8")}>
              <DatePicker onChange={onChange} />
              </div>
            </div>
          </div>
          <div className={cx("ant-col ant-col-sm-24 ant-col-xl-8")} />
        </div>
        {isLoading?<Skeleton/>:<Table
          columns={columns}
          dataSource={dataSource}
          // pagination={{ pageSize: pageSize }}
          rowKey={(record: any) => {
            return record.id;
          }}
          pagination={false}
          // onChange={handleTableChange}
        />}
         <div className={styles.pagination}>
        <Pagination
            style={{ marginTop: "3rem" }}
            pageSize={pageSize}
            onChange={onPaginationChange}
            current={pageNumber}
            total={totalData}
            onShowSizeChange={onPageSizeChange}
          />
          </div>
      </div>
    </>
  );
};

export default NewInvoiceList;
