import { useSelector } from 'react-redux';
import { GlobalAppExpDateData } from '../../../Features/BookingScreen/BookingData/BookingData';
import { useNavigate } from 'react-router-dom';
import { ArrowUpOutlined } from '@ant-design/icons';
import { StoredSessionData } from '../../../Features/ThemeChange/ThemeChange';
import ExtendSubscriptionModal from '../../ExtentedModal/ExtendSubscriptionModal';
import { useDispatch } from 'react-redux';
import {
  getPurchasedAppDetails,
  postInvoice,
} from '../../../Features/BookingScreen/Pricing/Pricing';
import { sendSms } from '../../../Features/Payment/PaymentDetails/PaymentDetails';
import { useEffect, useState, useMemo } from 'react';
import { encryptObject, getSession } from '../../../Services/Others';
import { GenerateLogout } from '../../../Features/BrachLogin/BranchLogin';
import { PublicQrCodepost } from '../../../Features/ConfigMasterPage/ConfigMasterPage';

const subDirectory = import.meta.env.ENV_BASE_URL;
const commonDirectory = import.meta.env.ENV_COMMON_BASE_URL;
console.log('commonDirectory', commonDirectory);
const PlanExpireNotification = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const AppExpDate = useSelector(GlobalAppExpDateData);
  const SessionData = useSelector(StoredSessionData);
  const [extendModel, setExtendModel] = useState(false);
  const {
    AppId,
    UserId,
    AppName,
    SessionId,
    AuthToken,
    CompId,
    SessionMobileNo,
    UserName,
    UserType,
  } = SessionData;
  console.log('SessionData', AppExpDate);
  const [count, setcount] = useState(0);
  const animations = ['example1', 'example2', 'example3'];
  let ss = animations[count];

  useEffect(() => {
    if (
      AppExpDate?.RemainingDays <= 7 ||
      AppExpDate?.PlanType?.toLowerCase() === 'extend'
    ) {
      const interval = setInterval(() => {
        setcount((prevCount) => (prevCount >= 2 ? 0 : prevCount + 1));
      }, 22000);
      return () => clearInterval(interval);
    }
  }, [count == 2]);

  // ================= DATE FORMAT =================
  const formatDate = (dateStr) => {
    const date = new Date(dateStr);
    return `${String(date.getDate()).padStart(2, '0')}-${String(date.getMonth() + 1).padStart(2, '0')}-${date.getFullYear()}`;
  };

  // ================= CHECK STATUS FLAGS =================
  const isExpired = useMemo(() => {
    return (
      AppExpDate?.RemainingDays <= 1 &&
      AppExpDate?.RemainingHours <= 1 &&
      AppExpDate?.RemainingMinutes <= 1 &&
      AppExpDate?.RemainingSeconds <= 1
    );
  }, [AppExpDate]);

  const isExtend = useMemo(() => {
    return AppExpDate?.PlanType?.toLowerCase() === 'extend';
  }, [AppExpDate]);

  const isExpiringToday =
    AppExpDate?.RemainingDays < 1 && !isExpired && !isExtend;
  const isExpiringSoon =
    AppExpDate?.RemainingDays >= 1 &&
    AppExpDate?.RemainingDays <= 30 &&
    !isExtend;

  // ================= AUTO OPEN EXTEND MODAL =================
  useEffect(() => {
    if (isExpired && !isExtend) {
      setExtendModel(true);
    }
  }, [isExpired, isExtend]);

  const handleCancel = () => {
    Logout();
    setExtendModel(false);
  };
  const Logout = async () => {
    const status = 'N';
    try {
      const res = await dispatch(GenerateLogout({ UserId, status })).unwrap();
      if (res?.data?.statusCode === 1) {
        sessionStorage.clear();
        window.location.replace(`${commonDirectory}`);
      }
    } catch (error) {
      console.error('Logout failed:', error);
    }
  };
  const handlePay = async () => {
    const response1 = await dispatch(
      getPurchasedAppDetails({ AppId, UserId })
    ).unwrap();
    const PurchasedDetails = response1?.data?.data;
    let data = {
      MN: SessionMobileNo,
      UN: UserName,
      UD: UserId,
      UT: UserType,
      CD: CompId,
      SD: SessionId || '',
      AU: AuthToken,
      Plandetails: PurchasedDetails?.[0],
    };
    const encrypted = encryptObject(data);
    const postData = { Url: encrypted, CreatedBy: UserId };
    try {
      const res = await dispatch(PublicQrCodepost(postData)).unwrap();
      // navigate(`${commonDirectory}invoice-details`);
      if (res?.data?.statusCode == 1) {
        navigate(`${commonDirectory}invoice-details/${res?.data?.ReferenceNo}`);
        setExtendModel(false);
      }
    } catch (error) {
      console.error('Error generating QR code:', error);
    }
  };

  // ================= UI BLOCKS =================
  const ExpiredBlock = () => (
    <div
      className="ExpiredMessage"
      style={{
        backgroundColor: '#ff4d4f',
        color: '#fff',
        fontSize: '13px',
        fontWeight: '500',
        fontFamily: 'Poppins',
        width: '100%',
      }}
    >
      Subscription expired &nbsp;
      <a onClick={handlePay} className="upgrdbtn">
        RENEWAL NOW <ArrowUpOutlined />
      </a>
    </div>
  );

  const ExpiringTodayBlock = () => (
    <p>
      Your application subscription will expire within &nbsp;
      <span className="Expired">
        {AppExpDate?.RemainingHours >= 1
          ? AppExpDate?.RemainingHours
          : AppExpDate?.RemainingMinutes}
      </span>{' '}
      {AppExpDate?.RemainingHours >= 1 ? 'Hrs' : 'Min'} &nbsp;
      <a onClick={handlePay} className="upgrdbtn">
        RENEWAL NOW <ArrowUpOutlined />
      </a>
    </p>
  );

  const ExpiringDaysBlock = () => (
    <p
      style={{
        backgroundColor: '#ff4d4f',
        color: '#fff',
        fontSize: '13px',
        fontWeight: '500',
        fontFamily: 'Poppins',
      }}
    >
      Your application subscription will expire within &nbsp;
      <span className="NosDays">{AppExpDate?.RemainingDays}</span> days. &nbsp;
      <a onClick={handlePay} className="upgrdbtn">
        RENEWAL NOW <ArrowUpOutlined />
      </a>
    </p>
  );

  // ================= RETURN =================
  return (
    <>
      {/* <div className={ ss : 'dd'}> */}
      <div className={isExtend ? 'dd' : ss} style={{ width: '100%' }}>
        {isExtend && <ExpiredBlock />}

        {isExpiringToday && <ExpiringTodayBlock />}

        {isExpiringSoon && <ExpiringDaysBlock />}
      </div>

      {extendModel && (
        <ExtendSubscriptionModal
          onClose={handleCancel}
          setExtendModel={setExtendModel}
          // onPayNow={handlePay}
          // onContinueWithCredits={freeExtend}
        />
      )}
    </>
  );
};

export default PlanExpireNotification;
