import { useEffect, useState, useCallback } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import {
  changeBreadCrumb,
  getEmpAccess,
} from '../../../Features/AppPage/CenterPage.js';
import { Messages } from '../../../Components/Notifications/Messages.jsx';
import FormHeader from '../../PageComponents/FormHeader.jsx';
import { Search } from '../../../Components/Forms/Search.jsx';
import Buttons from '../../../Components/Forms/Buttons.jsx';
import {
  EditFilled,
  DeleteFilled,
  PlusOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { AiOutlineMail } from 'react-icons/ai';
import { MdOutlineTextsms } from 'react-icons/md';
import { Checkbox, Space, Spin, Table } from 'antd';
import { Tables } from '../../../Components/Tables/Table.jsx';
import { getSession, dateFormatChange } from '../../../Services/Others.js';
import {
  getOfferCode,
  deleteOfferCode,
} from '../../../Features/Offer/OfferCode/OfferCode.js';
import { useAuth } from '../../../AuthContext.jsx';
import {
  getAllCustomer,
  getPreferenceData,
} from '../../../Features/BookingScreen/BookingData/BookingData.js';
import { DefaultModal } from '../../../Components/Modal/DefaultModal.jsx';
import { BiSolidCoupon } from 'react-icons/bi';
import {
  postCustomerOfferMail,
  postSMSOffer,
} from '../../../Features/Payment/PaymentDetails/PaymentDetails.js';
const CheckboxGroup = Checkbox.Group;
const subDirectory = import.meta.env.ENV_BASE_URL;

const items = [
  {
    name: 'Home',
    link: `${subDirectory}app-page/home`,
  },

  {
    name: 'Offercode',
    link: `${subDirectory}setting/offer-code`,
  },
];

const plainOptions = [
  {
    label: (
      <div
        style={{ display: 'flex', alignItems: 'center', marginTop: '0.2rem' }}
      >
        <AiOutlineMail size={18} style={{ marginRight: 5 }} />
        Mail
      </div>
    ),
    value: 'Mail',
  },
  {
    label: (
      <div
        style={{ display: 'flex', alignItems: 'center', marginTop: '0.2rem' }}
      >
        <MdOutlineTextsms size={18} style={{ marginRight: 5 }} />
        SMS
      </div>
    ),
    value: 'SMS',
  },
  // {
  //   label: (<><ShoppingOutlined style={{ marginRight: 8 }} />WatsApp</>),
  //   value: 'WatsApp',
  // },
];

const OfferCodeList = () => {
  const { SadminuserAccess } = useAuth();
  let SAAccessCommonMaster = SadminuserAccess?.find(
    (e) => e?.MenuName === 'Offer Code'
  );
  console.log(SadminuserAccess, 'SadminuserAccessSadminuserAccess');

  const dispatch = useDispatch();
  const location = useLocation();
  const navigateTo = useNavigate();

  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const UserType = getSession('UserType');

  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [searchedText, setSearchedText] = useState('');
  const [sortedInfo, setSortedInfo] = useState({});
  const [page, setpage] = useState(1);
  const [tabledata, setTabledata] = useState();
  const [Open, setOpen] = useState(false);
  const [empData, setEmpData] = useState();
  const [addnewAccess, setaddnewAccess] = useState(true);
  const [allowDecimal, setAllowDecimal] = useState(false);
  const [checkedList, setCheckedList] = useState([]);
  const [customerData, setCustomerData] = useState([]);
  const [page1, setpage1] = useState(1);
  const [sortedInfo1, setSortedInfo1] = useState({});
  const [selectedOfferCode, setSelectedOfferCode] = useState(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const checkAll = plainOptions.length === checkedList.length;
  const indeterminate =
    checkedList.length > 0 && checkedList.length < plainOptions.length;
  const getPreference = async () => {
    const data = { AppId: AppId, CompId: CompId, BranchId: BranchId };
    const { data: res } = await dispatch(getPreferenceData(data)).unwrap();
    const decimalSetting = res?.data?.[0]?.SettingDtlDetails?.find(
      (setting) =>
        setting?.SettingIdName?.toLowerCase() === 'decimal' &&
        setting?.SettingValue === 'Y'
    );
    if (decimalSetting) {
      setAllowDecimal(true);
    }
  };

  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
    if (location?.state?.Notiffy) {
      setMessageType(location?.state?.Notiffy.messageType);
      setMessageData(location?.state?.Notiffy.messageData);
    }
    TableData();
    getPreference();
    fetchCustomerApi();
    // if (UserType === "Employee") {
    //   fetchApi()
    // }
  }, []);
  useEffect(() => {
    if (UserType === 'Employee') {
      fetchApi();
    }
  }, [UserType]);

  useEffect(() => {
    let hasAccess = false;

    if (UserType === 'Admin' || UserType === 'Super Admin') {
      hasAccess = true;
    } else if (UserType === 'Employee') {
      hasAccess = empData?.AddAccess === 'Y';
    } else if (UserType === 'Super Admin User') {
      hasAccess = SAAccessCommonMaster?.AddAccess === 'Y';
    }

    setaddnewAccess(!hasAccess);
  }, [empData, SAAccessCommonMaster, UserType]);

  const fetchCustomerApi = async () => {
    let res = await dispatch(
      getAllCustomer({ CompId, AppId, branchId: BranchId })
    ).unwrap();
    if (res?.data?.statusCode === 1) {
      setCustomerData(
        res?.data?.data?.map((item, index) => ({ ...item, key: index + 1 }))
      );
    } else {
      setCustomerData([]);
    }
  };

  const fetchApi = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      EmpId: UserId,
    };
    let response = await dispatch(getEmpAccess(data)).unwrap();
    let datas = response?.data?.data?.[0]?.EmpAccessDetails?.filter(
      (item) => item.ConfigName === 'Offer Code'
    );
    setEmpData(datas?.[0]);
  };

  const TableData = async () => {
    let response = await dispatch(
      getOfferCode({ CompId: CompId, BranchId: BranchId, AppId: AppId })
    ).unwrap();
    if (response?.data?.statusCode == 1) {
      setTabledata(response?.data?.data);
    }
  };

  const onSearch = (value) => {
    setSearchedText(value);
  };

  const onSearchChange = (e) => {
    setSearchedText(e?.target?.value);
  };

  const handleChange = (pagination, filters, sorter) => {
    setSortedInfo(sorter);
  };

  const handlePageChange = (current) => {
    setpage(current);
  };

  const handelAddButton = () => {
    navigateTo(`${subDirectory}setting/offer-code/new`);
  };

  const actionsFormatter = async (row, rowIndex) => {
    if (row.ActiveStatus !== 'D') {
      navigateTo(
        `${subDirectory}setting/offer-code/update`,
        { state: { editstate: row } },
        { key: rowIndex }
      );
    }
  };
  const statusFormatter = async (row) => {
    let deleteData = {
      uniqueId: row?.UniqueId,
      updatedBy: UserId,
      activeStatus: row?.ActiveStatus == 'A' ? 'D' : 'A',
    };
    let response = await dispatch(deleteOfferCode(deleteData)).unwrap();
    if (response?.data?.statusCode === 1) {
      TableData();
      setMessageType('success');
      setMessageData(
        row.ActiveStatus == 'A'
          ? 'In-Activated Successfully'
          : 'Activated Successfully'
      );
    } else if (response?.data?.statusCode === 0) {
      setMessageType('error');
      setMessageData(response?.data?.response);
    }
  };

  function safeRound(amountStr) {
    if (amountStr == null) return allowDecimal ? '0.00' : '0';

    const cleaned = String(amountStr).replace(/[^0-9.-]+/g, '');
    const num = Number(cleaned);

    if (isNaN(num)) return allowDecimal ? '0.00' : '0';

    return allowDecimal ? num.toFixed(2) : Math.round(num).toString();
  }
  const columns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      // width: "50px",
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'Offer Name',
      dataIndex: 'OfferName',
      key: 'OfferName',
      // width: "100px",
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      filteredValue: [searchedText],
      onFilter: (value, record) => {
        return (
          String(record.OfferName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.MinQty)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.MinPurchase)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.Point)?.toLowerCase()?.includes(value?.toLowerCase()) ||
          String(record.RewardTypeName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase())
        );
      },
      sorter: (a, b) => a?.OfferName?.length - b?.OfferName?.length,
      sortOrder: sortedInfo.columnKey === 'OfferName' ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: 'Min Qty',
      dataIndex: 'MinQty',
      key: 'MinQty',
      // width: "90px",
      align: 'right',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
    },
    {
      title: 'Min Purchase',
      dataIndex: 'MinPurchase',
      key: 'MinPurchase',
      // width: "95px",
      align: 'right',
      render: (text) => <a style={{ color: 'black' }}>{safeRound(text)}</a>,
    },
    {
      title: 'Offer Code',
      dataIndex: 'OfferCode',
      key: 'OfferCode',
      width: '180px',
      align: 'center',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
    },
    {
      title: 'Reward Type',
      dataIndex: 'RewardTypeName',
      key: 'RewardTypeName',
      // width: "90px",
      align: 'right',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
    },
    {
      title: 'Reward Value',
      dataIndex: 'Discount',
      key: 'Discount',
      // width: "100px",
      align: 'center',
      render: (_, record, index) => (
        <a style={{ color: 'black' }}>
          {record?.RewardTypeName === 'Discount' ? (
            record?.OfferType == 'F' ? (
              '₹' + safeRound(record?.OfferAmt)
            ) : (
              record?.OfferAmt + '%'
            )
          ) : (
            <div style={{ fontSize: '12px' }}>
              {record?.RewardTypeDetails.length + ' ' + 'Products'}
            </div>
          )}
        </a>
      ),
    },
    {
      title: 'From',
      dataIndex: 'OfferFrom',
      key: 'OfferFrom',
      width: '120px',
      render: (text) => (
        <a style={{ color: 'black' }}>{dateFormatChange(text)}</a>
      ),
    },
    {
      title: 'To',
      dataIndex: 'OfferTo',
      key: 'OfferTo',
      width: '120px',
      render: (text) => (
        <a style={{ color: 'black' }}>{dateFormatChange(text)}</a>
      ),
    },
    {
      title: 'Share Offer Code',
      dataIndex: 'OfferId',
      key: 'OfferId',
      width: '100px',
      align: 'center',
      render: (text, record) => (
        <div
          onClick={() =>
            record.ActiveStatus === 'A'
              ? (UserType === 'Super Admin' ||
                  (UserType === 'Super Admin User' &&
                    SAAccessCommonMaster?.UpdateAccess === 'Y') ||
                  (UserType === 'Employee' &&
                    (empData?.UpdateAccess === 'Y' ||
                      empData?.AddAccess === 'Y')) ||
                  UserType === 'Admin') &&
                handleShareOfferCode(record)
              : null
          }
          style={{
            cursor: record.ActiveStatus === 'A' ? 'pointer' : 'not-allowed',
            color: record.ActiveStatus === 'A' ? '#1677ff' : 'gray',
            opacity: record.ActiveStatus === 'A' ? 1 : 0.5,
            pointerEvents: record.ActiveStatus === 'A' ? 'auto' : 'none',
          }}
        >
          <BiSolidCoupon style={{ fontSize: '20px' }} />
        </div>
      ),
    },
    {
      title: 'Action',
      key: 'Action',
      align: 'center',
      dataIndex: 'Action',
      render: (_, record, index) =>
        tabledata.length >= 1 ? (
          <Space size="middle">
            {record.ActiveStatus === 'A' ? (
              <a>
                <EditFilled
                  style={{ color: '#1292EE' }}
                  onClick={() =>
                    UserType === 'Super Admin' ||
                    (UserType === 'Super Admin User' &&
                      SAAccessCommonMaster?.UpdateAccess === 'Y') ||
                    (UserType === 'Employee' &&
                      empData?.UpdateAccess === 'Y') ||
                    UserType === 'Admin'
                      ? actionsFormatter(record, index)
                      : null
                  }
                />
              </a>
            ) : (
              ''
            )}
            <a>
              {record.ActiveStatus === 'A' ? (
                <DeleteFilled
                  style={{
                    color: '#FF4D4F',
                  }}
                  onClick={() =>
                    UserType === 'Super Admin' ||
                    (UserType === 'Super Admin User' &&
                      SAAccessCommonMaster?.DeleteAccess === 'Y') ||
                    (UserType === 'Employee' &&
                      empData?.DeleteAccess === 'Y') ||
                    UserType === 'Admin'
                      ? statusFormatter(record, index)
                      : null
                  }
                />
              ) : (
                <ReloadOutlined
                  style={{
                    color: '#52C41A',
                  }}
                  onClick={() =>
                    UserType === 'Super Admin' ||
                    (UserType === 'Super Admin User' &&
                      SAAccessCommonMaster?.DeleteAccess === 'Y') ||
                    (UserType === 'Employee' &&
                      empData?.DeleteAccess === 'Y') ||
                    UserType === 'Admin'
                      ? statusFormatter(record, index)
                      : null
                  }
                />
              )}
            </a>
          </Space>
        ) : null,
    },
  ];

  const columns1 = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '100px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page1 - 1) * 10 + index + 1}</a>
      ),
    },

    {
      title: 'Customer ID',
      dataIndex: 'CustId',
      key: 'CustId',
      width: '150px',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      filteredValue: [searchedText],
      onFilter: (value, record) => {
        return (
          String(record.OfferName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.MinQty)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.MinPurchase)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.Point)?.toLowerCase()?.includes(value?.toLowerCase()) ||
          String(record.RewardTypeName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase())
        );
      },
      sorter: (a, b) => a?.OfferName?.length - b?.OfferName?.length,
      sortOrder:
        sortedInfo1.columnKey === 'OfferName' ? sortedInfo1.order : null,
      ellipsis: true,
    },
    {
      title: 'Cust Name',
      dataIndex: 'CustName',
      key: 'CustName',
      width: '80px',
      align: 'right',
    },
    {
      title: 'Cust Mobile No',
      dataIndex: 'CustMobile',
      key: 'CustMobile',
      width: '120px',
      align: 'right',
    },
    {
      title: 'Cust Email',
      dataIndex: 'CustEmail',
      key: 'CustEmail',
      width: '150px',
      align: 'center',
    },
  ];

  const handleShareOfferCode = async (record) => {
    setSelectedOfferCode(record);
    setOpen((prev) => !prev);
  };

  const onCheckAllChange = (e) => {
    setCheckedList(
      e.target.checked ? plainOptions?.map(({ value }) => value) : []
    );
  };

  const onChange = (list) => {
    setCheckedList(list);
  };

  const handlePage1Change = (current) => {
    setpage1(current);
  };

  const handleChange1 = (pagination, filters, sorter) => {
    setSortedInfo1(sorter);
  };

  const onSelectChange = (newSelectedRowKeys) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const handleSubmit = async () => {
    if (checkedList?.includes('Mail') || checkedList?.includes('SMS')) {
      const selectedCustomers = customerData?.filter((_, index) =>
        selectedRowKeys.includes(index)
      );
      if (selectedCustomers?.length > 0) {
        const { BrName, BrEmail } = selectedCustomers?.[0] || {};
        const {
          OfferCode,
          Description,
          MinQty,
          MinPurchase,
          RewardTypeName,
          AppliesTo,
          OfferAmt,
          ProdCount,
          RewardOrderTypeDetails,
          RewardTypeDetails,
          RewardFreeTypeDetails,
        } = selectedOfferCode;
        let response = { mail: '', sms: '' };
        setIsLoading(true);

        if (checkedList?.includes('Mail')) {
          const applicableEmailCustomers =
            selectedCustomers
              ?.filter(({ CustEmail }) => CustEmail !== null)
              ?.map(({ CustId, CustName, CustMobile, CustEmail }) => ({
                CustId,
                CustName,
                CustMobile,
                CustEmail,
              })) || [];
          if (applicableEmailCustomers?.length > 0) {
            let Categories = '';
            let Products = '';
            if (RewardTypeName === 'Discount' && AppliesTo === 'S') {
              Categories = RewardOrderTypeDetails?.filter(
                ({ ProdCat }) => ProdCat !== 0 || ProdCat !== null
              )
                ?.map(({ ProdCatName }) => ProdCatName)
                ?.filter(Boolean)
                .join();
              Products = RewardOrderTypeDetails?.filter(
                ({ ProdCat }) => ProdCat === 0 || ProdCat === null
              )
                ?.map(({ ProdName }) => ProdName)
                ?.filter(Boolean)
                .join();
            } else if (RewardTypeName === 'Free Products') {
              Products = [
                ...RewardTypeDetails?.map(({ ProdName }) => ProdName),
                ...RewardFreeTypeDetails?.map(({ ProdName }) => ProdName),
              ]
                ?.filter(Boolean)
                .join();
            }
            const postEmailData = {
              BrName,
              BrEmail,
              Description,
              MinQty,
              MinPurchase,
              OfferCode,
              CustomerDtl: applicableEmailCustomers,
              RewardTypeName,
              AppliesTo,
              Categories,
              Products,
              Amount: OfferAmt,
              Qty: ProdCount,
            };
            response.mail = await dispatch(
              postCustomerOfferMail(postEmailData)
            ).unwrap();
          }
        }

        if (checkedList?.includes('SMS')) {
          const applicableSMSCustomers =
            selectedCustomers
              ?.filter(({ CustMobile }) => CustMobile !== null)
              ?.map(({ CustId, CustName, CustMobile, CustEmail }) => ({
                CustId,
                CustName,
                CustMobile,
                CustEmail,
              })) || [];
          if (applicableSMSCustomers?.length > 0) {
            let Categories = '';
            let Products = '';
            if (RewardTypeName === 'Discount' && AppliesTo === 'S') {
              Categories = RewardOrderTypeDetails?.filter(
                ({ ProdCat }) => ProdCat !== 0 || ProdCat !== null
              )
                ?.map(({ ProdCatName }) => ProdCatName)
                ?.filter(Boolean)
                .join();
              Products = RewardOrderTypeDetails?.filter(
                ({ ProdCat }) => ProdCat === 0 || ProdCat === null
              )
                ?.map(({ ProdName }) => ProdName)
                ?.filter(Boolean)
                .join();
            } else if (RewardTypeName === 'Free Products') {
              Products = [
                ...RewardTypeDetails?.map(({ ProdName }) => ProdName),
                ...RewardFreeTypeDetails?.map(({ ProdName }) => ProdName),
              ]
                ?.filter(Boolean)
                .join();
            }
            const postSMSData = {
              BrName,
              BrEmail,
              Description,
              MinQty,
              MinPurchase,
              OfferCode,
              CustomerDtl: applicableSMSCustomers,
              RewardTypeName,
              AppliesTo,
              Categories,
              Products,
              Amount: OfferAmt,
              Qty: ProdCount,
            };

            response.sms = await dispatch(postSMSOffer(postSMSData)).unwrap();
          }
        }

        setIsLoading(false);
        setOpen((prev) => !prev);
        setSelectedRowKeys([]);
        setCheckedList([]);
        if (
          response?.mail?.data?.statusCode === 1 ||
          response?.sms?.data?.statusCode === 1
        ) {
          setMessageType('success');
          setMessageData(
            `${response?.mail?.data?.response} & ${response?.sms?.data?.response}`
          );
          return;
        } else {
          setMessageType('error');
          setMessageData('Failed to send Email and SMS');
          return;
        }
      } else {
        setMessageType('error');
        setMessageData('Choose Customer');
      }
    } else {
      setMessageType('error');
      setMessageData(
        'Please select at least one communication method (Mail/SMS)'
      );
    }
  };

  const handleCancel = () => {
    setOpen((prev) => !prev);
    setSelectedRowKeys([]);
  };

  return (
    <>
      <div className="userPageTable">
        <div className="userPageContent">
          <div className="formAddNew">
            <Messages
              messageType={messageType}
              messageData={messageData}
              onComplete={onComplete}
            />
            <div>
              <FormHeader title={'Offer Code'} />
            </div>
            <div className="searchAddDiv" style={{ marginBottom: '1rem' }}>
              <div className="formSearch">
                <Search
                  placeholder="Search"
                  onSearch={onSearch}
                  onSearchChange={onSearchChange}
                />
              </div>

              <Buttons
                buttonText={'Add New'}
                handleSubmit={() => handelAddButton()}
                color="901D77"
                disabled={addnewAccess}
                icon={<PlusOutlined />}
              >
                OPEN
              </Buttons>
            </div>
          </div>
          <div className="reportTable">
            <Tables
              columns={columns}
              data={tabledata}
              dataSource={tabledata}
              pagination={handlePageChange}
              onChange={handleChange}
            />
          </div>
          <DefaultModal
            open={Open}
            title="Share Offer Code"
            footer={true}
            width={1100}
            children={
              <>
                <Spin spinning={isLoading} tip="Sending...">
                  <div
                    style={{
                      display: 'flex',
                      flexDirection: 'column',
                      gap: '0.5rem',
                      border: '1px solid #d9d9d9',
                      padding: '0.5rem',
                      borderRadius: '0.50rem',
                    }}
                  >
                    <p style={{ fontSize: '14px', fontWeight: '500' }}>
                      Share Codes via :
                    </p>
                    <Checkbox
                      indeterminate={indeterminate}
                      onChange={onCheckAllChange}
                      checked={checkAll}
                    >
                      Check All
                    </Checkbox>
                    <CheckboxGroup
                      options={plainOptions}
                      value={checkedList}
                      onChange={onChange}
                    />
                  </div>
                  <Table
                    rowSelection={rowSelection}
                    columns={columns1}
                    dataSource={customerData}
                    pagination={{
                      onChange: handlePage1Change,
                      defaultPageSize: 10,
                      showSizeChanger: false,
                      hideOnSinglePage: true,
                    }}
                    onChange={handleChange1}
                  />
                </Spin>
              </>
            }
            handleSubmit={handleSubmit}
            handleCancel={handleCancel}
          />
        </div>
      </div>
    </>
  );
};

export default OfferCodeList;
