import { FC, useEffect, useState } from "react";
import styles from "./giftSheetManager.module.scss";
import { Button, Input, notification, Popconfirm, Skeleton, Space, Table } from "antd";
import {
  SearchOutlined,
  DeleteOutlined,
  DownloadOutlined,
  PlusCircleOutlined,
  QuestionCircleOutlined
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import moment from "moment";
import cx from "classnames";
import * as GiftSheetAPI from "../../../pages/api/productDetails/uploadGiftSheet";
import GiftSheetModal from "../../modal/giftSheetModal/GiftSheetModal";


const GiftSheetManager: FC<any> = () => {

  const [loginRes, setLoginRes] = useState<any>({});
  const [giftSheetList, setGiftSheetList] = useState([]);
  // const [newGiftSheetList, setNewGiftSheetList] = useState([]);
  // const [value, setValue] = useState("");
  const [loading, setLoading] = useState(false);
  const [info, setInfo] = useState<any>({ title: '', desc: '', status: '' });
  const [showGiftModal, setShowGiftModal] = useState<boolean>(false);
  const [giftSheetExcel, setGiftSheetExcel] = useState<any>(null);
  const [giftData, setGiftData] = useState<any>({});
  const [modalType, setModalType] = useState<string>('');

  const columns: ColumnsType<any> = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      width: 60,
      render: (text) => {
        return <div style={{ width: "40px" }}>{text}</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) => {
        return moment(object?.created_at).format("DD-MM-YYYY");
      },
    },
    {
      title: "Updated at",
      dataIndex: "updated_at",
      key: "updated_at",
      responsive: ["xs", "xl", "md"],
      sorter: (a: any, b: any) =>
        moment(a.updated_at).format("DD-MM-YYYY") &&
          moment(a.updated_at).format("DD-MM-YYYY") >
          moment(b.updated_at).format("DD-MM-YYYY") &&
          moment(b.updated_at).format("DD-MM-YYYY")
          ? 1
          : -1,
      render: (object: any) => {
        return moment(object?.updated_at).format("DD-MM-YYYY");
      },
    },
    {
      title: "Gift Sheet Name",
      dataIndex: "title",
      key: "title",
      responsive: ["xs", "xl", "md"],
      sorter: (a: any, b: any) =>
        a?.title.localeCompare(b?.title),

      render: (text) => {
        return text;
      },
    },

    {
      title: "Description",
      dataIndex: "description",
      key: "description",
      responsive: ["xs", "xl", "md"],
      render: (text) => {
        return text;
      },
    },
    {
      title: "Status",
      dataIndex: "status",
      key: "status",
      responsive: ["xl", "md"],
      render: (text) => {
        const status = text == "1" ? "Active" : "Inactive";
        return status;
      },
    },
    {
      title: "Action",
      key: "action",
      responsive: ["xl", "md"],
      render: (object: any) => (
        <Space size="middle" className={styles.buttonsSelection}>
          <a href={object?.url} target="_blank" type="primary" className={styles.buttonsCart} rel="noreferrer">
            <DownloadOutlined title="Download" />
          </a>
          <Button type="primary" onClick={() => addUpdateGiftSheet(object, "update")}>Update</Button>
          <Popconfirm
            title="Delete this sheet"
            onConfirm={() => deleteGiftSheet(object?.id)}
            icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
            okText="Yes"
            cancelText="No"
          >
            <DeleteOutlined style={{ color: 'red', fontSize: "20px" }} />
          </Popconfirm>
        </Space>
      ),
    }
  ];

  useEffect(() => {
    setLoading(true);
    const val: any = localStorage.getItem("loginDetails");
    const details: any = JSON.parse(val);
    setLoginRes(details);
    GiftSheetAPI.getGiftSheetsApi({ token: details?.token }).then((res) => {
      if (res?.status) {
        setGiftSheetList(res?.sheets);
        // setNewGiftSheetList(res?.sheets);
        setLoading(false);
      }
    })
  }, [])

  const deleteGiftSheet = (data: any) => {
    const params = {
      id: data,
      token: loginRes?.token
    };
    GiftSheetAPI.deleteGiftSheet(params).then((res) => {
      if (res?.status) {
        notification.success({ message: 'Success! Gift Sheet has been deleted successfully' });

        GiftSheetAPI.getGiftSheetsApi({ token: loginRes?.token }).then((res_sheet) => {
          if (res_sheet?.status) {
            setGiftSheetList(res_sheet.sheets);
            // setNewGiftSheetList(res?.sheets);
          }
        });
      }
    })
  };

  const addUpdateGiftSheet = (obj: any, type: string) => {
    setShowGiftModal(true);
    setGiftData(obj);
    setModalType(type);
  }

  const uploadGiftSheet = () => {
    if (giftSheetExcel?.name) {
      const payload = { gift_sheet: giftSheetExcel, title: info?.title, description: info?.desc, token: loginRes?.token };
      GiftSheetAPI.uploadGiftSheetApi(payload).then((res) => {
        if (res?.status) {
          notification.success({ message: 'Success! Gift Sheet has been added successfully' });

          GiftSheetAPI.getGiftSheetsApi({ token: loginRes?.token }).then((res_sheet) => {
            if (res_sheet?.status) {
              setGiftSheetList(res_sheet.sheets);
              // setNewGiftSheetList(res?.sheets);
            }
          });
        }
      });
      setShowGiftModal(false);
      setInfo({ title: '', desc: '', status: '' });
      setGiftData({});
      setGiftSheetExcel(null);
      setModalType('');
    } else {
      notification.warn({ message: 'Warning! Gift Sheet is required' });
    }
  }

  const updateGiftSheet = () => {
    const finalPayload = {
      id: giftData?.id,
      title: info?.title,
      description: info?.desc,
      status: info?.status !== '' ? info?.status === "Active" ? "1" : "0" : giftData?.status,
      gift_sheet: giftSheetExcel,
      token: loginRes?.token
    };
    GiftSheetAPI.updateGiftSheetApi(finalPayload).then((res) => {
      if (res?.status) {
        GiftSheetAPI.getGiftSheetsApi({ token: finalPayload.token }).then((res_sheet) => {
          if (res_sheet?.status) {
            setGiftSheetList(res_sheet.sheets);
            // setNewGiftSheetList(res?.sheets);
          }
        });
        notification.success({ message: 'Success! Gift Sheet has been updated successfully' });
      }
    });
    setInfo({ title: '', desc: '', status: '' });
    setGiftSheetExcel(null);
    setGiftData({});
    setShowGiftModal(false);
    setModalType('');
  };



  return (
    <>
      <div className={styles.container}>
        <h1 className={styles.title} >Gift Sheet Manager</h1>
        <div className={cx("items-self")}>
          <div className={cx("ant-row my-4 flex justify-between")}>
            {/* <div >
                                <Input
                                    value={value}
                                    placeholder="Search"
                                    style={{ width: 200 }}
                                    allowClear={true}
                                    suffix={<SearchOutlined />}
                                    size={"middle"}
                                    onChange={(e: any) => {
                                        if (e.target.value === "") {
                                            setGiftSheetList(newGiftSheetList);
                                            setValue("");
                                        } else if (e?.nativeEvent?.inputType == "deleteContentBackward") {
                                            const currValue = e.target.value.toLowerCase();
                                            setValue(currValue);
                                            const removeFilter = newGiftSheetList;
                                            const filteredData = removeFilter.filter((entry: any) => {
                                                const name = entry?.title.toLowerCase()
                                                return name.includes(currValue);
                                            });
                                            setGiftSheetList(filteredData);
                                        } else {
                                            const currValue = e.target.value.toLowerCase();
                                            setValue(currValue);
                                            const filteredData = giftSheetList.filter((entry: any) => {
                                                const name = entry?.title;
                                                const final_name = name.toLowerCase();
                                                return final_name.includes(currValue);
                                            });
                                            setGiftSheetList(filteredData);
                                        }
                                    }}
                                />
                            </div> */}
            <div className="mx-3">
              <Button type="primary" className={cx(styles.buttonsCart, "flex item-center justify-center w-24")} onClick={() => addUpdateGiftSheet({}, "add")}>
                <PlusCircleOutlined />
                Add
              </Button>
            </div>
            <div className="mx-3">
              Total {giftSheetList.length} Sheets found.
            </div>
          </div>
        </div>
        {loading ? <Skeleton /> : <Table
          columns={columns}
          dataSource={giftSheetList}
          className={styles.tablePlus}
          //onChange={onChange}
          rowKey={(record: any) => {
            return record?.id;
          }}
          scroll={{ x: 1400 }}
        />}

      </div>
      <GiftSheetModal
        hasDescription
        modalType={modalType}
        info={info}
        setInfo={setInfo}
        giftData={giftData}
        setGiftData={setGiftData}
        giftSheetExcel={giftSheetExcel}
        isGiftModal={showGiftModal}
        setIsGiftModal={setShowGiftModal}
        setGiftSheetExcel={setGiftSheetExcel}
        uploadGiftSheet={Object.keys(giftData).length > 0 ? updateGiftSheet : uploadGiftSheet}
      />
    </>
  )
}

export default GiftSheetManager;