import { UploadOutlined } from "@ant-design/icons";
import { Collapse, Input, Modal, Select } from "antd";
import { FC, useEffect, useState } from "react";
import * as GiftSheetAPI from "../../../pages/api/productDetails/uploadGiftSheet";
import styles from "./giftSheetModal.module.scss";

const { Panel } = Collapse;

const GiftSheetModal: FC<any> = (props) => {
  const { giftSheetExcel, isGiftModal, setIsGiftModal, setGiftSheetExcel, uploadGiftSheet } = props;
  const [title, setTitle] = useState<string>(props?.giftData?.title);
  const [description, setDescription] = useState<string>(props?.giftData?.description);
  const [status, setStatus] = useState<string>(props?.giftData?.status == "1" ? "Active" : "Inactive");
  const [giftSheetList, setGiftSheetList] = useState<any>([]);
  const [selectValue, setSelectValue] = useState<any>(props?.giftSheetExcelObj || {});
  const [activeKey, setActiveKey] = useState<string>("1");
  const [giftSheet, setGiftSheet] = useState<{ type: string; file: any }>({ type: '', file: null });

  useEffect(() => {
    if (props?.hasDescription) {
      setTitle(props?.giftData?.title);
      setDescription(props?.giftData?.description);
      setStatus(props?.giftData?.status == "1" ? "Active" : "Inactive");
    }
  }, [props?.giftData])

  useEffect(() => {
    if (props?.addSheetToProduct && isGiftModal) {
      const val: any = localStorage.getItem("loginDetails");
      const details: any = JSON.parse(val);
      GiftSheetAPI.getGiftSheetsApi({ token: details?.token }).then((res) => {
        if (res?.status) {
          setGiftSheetList([{ label: "Select a Gift Sheet", value: '' }, ...(res?.sheets || []).map((sheet: any) => ({ ...sheet, label: sheet?.title, value: sheet?.id }))]);
        }
      })
    }
    setSelectValue('');
  }, [isGiftModal])

  const handleGiftSheetInput = (event: any) => {
    event.preventDefault();
    if (event?.target?.files?.length > 0) setGiftSheet({ type: 'new', file: event?.target?.files[0] });
    //props?.setGiftSheetExcelObj && props?.setGiftSheetExcelObj({});
    // props?.setISNewGiftSheet && props?.setISNewGiftSheet(true);
  };

  const handleGiftSheetModalClose = () => {
    setIsGiftModal(false);
    if (props?.hasDescription) {
      setTitle('');
      setDescription('');
      props?.setGiftData && props?.setGiftData({});
    }
    if (props?.modalType === "addDetails") {
      setGiftSheetExcel(null);
      props?.setGiftSheetExcelObj && props?.setGiftSheetExcelObj({});
      props?.setIsGift && props?.setIsGift(false);
      setSelectValue('');
    }
    if (props?.modalType === "updateDetails") {
      !giftSheetExcel && setGiftSheetExcel(giftSheetExcel);
      (Object.keys(props?.giftSheetExcelObj).length !== 0) && props?.setGiftSheetExcelObj && props?.setGiftSheetExcelObj(props?.giftSheetExcelObj);
    }
    setGiftSheet({type: '', file: null});
  };

  const handleStatusChange = (value: string) => {
    props?.setInfo && props?.setInfo({ ...props?.info, status: value });
    setStatus(value);
  };

  const handleSheetChange = (value: any) => {
    const sheet = { ...(giftSheetList.find((sheet: any) => sheet?.id == value) || []) } || {};
    setGiftSheet({ type: 'list', file: sheet });
    setSelectValue(value);
  }

  const handleActiveKey = (value: any) => {
    setActiveKey(value);
  }

  const handleGiftSheetModal = () => {
    if (giftSheet.type === "list") {
      props?.setGiftSheetExcelObj && props?.setGiftSheetExcelObj(giftSheet.file);
      setGiftSheetExcel(null);
      props?.setISNewGiftSheet && props?.setISNewGiftSheet(false);
    }
    if (giftSheet.type === "new") {
      setGiftSheetExcel(giftSheet.file);
      props?.setGiftSheetExcelObj && props?.setGiftSheetExcelObj({});
      props?.setISNewGiftSheet && props?.setISNewGiftSheet(true);

    }
    uploadGiftSheet();
  }

  const resetInputField = (e: any) => {
    e.target.value = '';
  }

  const heading = props?.modalType === "add"
    ? "Add a New Gift Sheet" : props?.modalType === "update"
      ? "Update the Gift Sheet" : props?.isCheckOutModal
        ? "Please Select a Gift Sheet to Update" : "Please Select a Gift Sheet";

  return (
    <Modal
      title={heading}
      visible={isGiftModal}
      onCancel={handleGiftSheetModalClose}
      onOk={handleGiftSheetModal}
    >
      {
        props?.hasDescription && <div>
          <div className="mb-3.5">
            <span>Title :&nbsp;</span>
            <Input
              placeholder={"Add Title"}
              value={title}
              onChange={(e) => {
                props?.setInfo({ ...props?.info, title: e?.target?.value });
                setTitle(e?.target?.value);
              }}
            />
          </div>
          <div className="mb-3.5">
            <span>Description :&nbsp;</span>
            <Input
              placeholder={"Add Description"}
              value={description}
              onChange={(e) => {
                props?.setInfo({ ...props?.info, desc: e?.target?.value });
                setDescription(e?.target?.value);
              }}
            />
          </div>
          {
            props?.modalType === "update" && <div className="mb-3.5 flex justify-between w-64 items-center">
              <span>Status :&nbsp;</span>
              <Select
                value={status}
                style={{ width: 120 }}
                onChange={handleStatusChange}
                options={[
                  { value: 'Inactive', label: 'Inactive' },
                  { value: 'Active', label: 'Active' }
                ]}
              />
            </div>
          }
          <label className={giftSheetExcel ? styles.uploadExcelFile : styles.uploadExcelFileBefore}>
            <UploadOutlined />
            <input style={{ display: "none" }} name="excel" type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" onChange={handleGiftSheetInput} onClick={resetInputField} />
            {giftSheet.file && giftSheet.file.name ? giftSheet.file.name : giftSheetExcel ? giftSheetExcel.name : Object.keys(props?.giftData || {}).length > 0 ? props?.giftData?.title : "Upload Excel File"}
          </label>
        </div>
      }
      {
        props?.addSheetToProduct && <div>
          <Collapse accordion activeKey={activeKey} onChange={handleActiveKey}>
            <Panel header="Select from Gift Sheet List" key="1">
              <div className="mb-3.5 flex justify-between items-center">
                <span>Select a Gift Sheet :&nbsp;</span>
                <Select
                  style={{ width: 200 }}
                  placeholder="Select a Gift Sheet"
                  value={giftSheetList.find((sheet: any) => sheet.value === selectValue)}
                  onChange={handleSheetChange}
                  options={giftSheetList.filter((sheet: any) => { if (sheet?.status == "1") return sheet })}
                />
              </div>
            </Panel>
            <Panel header="Upload the Gift Sheet" key="2">
              <div>
                <label className={giftSheetExcel ? styles.uploadExcelFile : styles.uploadExcelFileBefore}>
                  <UploadOutlined />
                  <input style={{ display: "none" }} name="excel" type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" onChange={e => handleGiftSheetInput(e)} onClick={resetInputField} />
                  {giftSheet.file ? giftSheet.file.name ? giftSheet.file.name : "Upload Excel File" :  "Upload Excel File"}
                </label>
              </div>
            </Panel>
          </Collapse>
        </div>
      }
      {
        props?.isCheckOutModal && <div>
          <label className={giftSheetExcel ? styles.uploadExcelFile : styles.uploadExcelFileBefore}>
            <UploadOutlined />
            <input style={{ display: "none" }} name="excel" type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" onChange={e => handleGiftSheetInput(e)} onClick={resetInputField} />
            {giftSheet.file && giftSheet.file.name ? giftSheet.file.name : giftSheetExcel ? giftSheetExcel.name : props?.giftSheetTitle ? props?.giftSheetTitle : "Upload Excel File" }
          </label>
        </div>
      }
    </Modal>
  )
}

export default GiftSheetModal;