// 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 { useState } from "react";
// const subDirectory = import.meta.env.BASE_URL;
// const commonDirectory = import.meta.env.COMMON_BASE_URL;
   
// const PlanExpireNotification = ({ss}) => {
//     const navigate = useNavigate();
//     const dispatch = useDispatch();
    
//     const AppExpDate = useSelector(GlobalAppExpDateData);
//     const SessionData = useSelector(StoredSessionData);
//     const [extendModel, setExtendModel] = useState(false);
//     console.log("AppExpDate", AppExpDate);
//       const navigateFun = () => {
//           navigate(`${subDirectory}PricingPage`, { state: { AppName: SessionData?.AppName } });
//         };
      
//         const navigatePublicFun = () => {
//           navigate(`${commonDirectory}`);
//         };
//          const formatDate = (dateStr) => {
//             const date = new Date(dateStr);
//             const year = date.getFullYear();
//             const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
//             const day = String(date.getDate()).padStart(2, '0');
//             return `${day}-${month}-${year}`;
//             };
//         const freeExtend = async () => {
//     try {
//       const { CompId, AppId, BranchId, UserType,UserId } = SessionData;

//       // Current date
//       const now = new Date();
//       const currentDate = formatDate(now);

//       // 1️⃣ Get purchased app details
//       const response1 = await dispatch(
//         getPurchasedAppDetails({ AppId, UserId })
//       ).unwrap();

//       const PurchasedDetails = response1?.data?.data;

//       if (!PurchasedDetails || !PurchasedDetails.length) {
//         console.error('No purchased details found');
//         return;
//       }

//       // 2️⃣ Prepare post data
//       const postData = {
//         UserId: UserId,
//         AppId: AppId,
//         PricingId: PurchasedDetails[0]?.PricingId,
//         PurDate: currentDate,
//         NoofDays: 30,
//         PaymentMode: 27,
//         PaymentStatus: 'S',
//         LicenseStatus: PurchasedDetails[0]?.LicenseStatus,
//         Price: PurchasedDetails[0]?.Price ?? 0,
//         TaxId: PurchasedDetails[0]?.TaxId ?? 0,
//         NetPrice: PurchasedDetails[0]?.ExistingPlanNetPrice ?? 0,
//         ValidityStart: currentDate,
//         ValidityEnd: addDays(
//           currentDate,
//           PurchasedDetails[0]?.NoOfDays
//         ),
//         CreatedBy: UserId,
//         TaxAmount: PurchasedDetails[0]?.TaxAmount ?? 0,
//         MobileNo: getSession('MobileNo'),
//         MailId: 'ts@gmmail.com',
//         Type: "FreeExtend"
//       };

//       // 3️⃣ Post invoice
//       const response = await dispatch(postInvoice(postData)).unwrap();

//       // 4️⃣ Send SMS if required
//       if (response?.data?.statusCode === 1 && response?.data?.SMSbody) {
//         await dispatch(
//           sendSms({ body: response.data.SMSbody })
//         );
//         setExtendModel(false)

//       }

//     } catch (error) {
//       console.error('freeExtend error:', error);
//     }
//   };
//   const handleCancel = () => {
//     Logout();
//     setExtendModel(false)

//   }
//   const handlePay = () => {
//     setExtendModel(false)
//     let AppName = getSession("AppName")
//     navigate(`${subDirectory}PricingPage`, { state: { AppName: AppName } });
//   }

//     return(
//         <>
//             <div className={`${ss}`}>
//             <p>
//               {(AppExpDate?.RemainingDays < 30 &&
//                 AppExpDate?.RemainingHours < 30 &&
//                 AppExpDate?.RemainingMinutes < 50 &&
//                 AppExpDate?.RemainingSeconds < 60
//               ) ||
//               AppExpDate === 'undefined' ? (
//                 (AppExpDate?.PlanType?.toLowerCase() == "extend expired")?(

//                 <span className="ExpiredMessage"> 
//                   Subscription expired &nbsp;
//                   <a
//                     onClick={() => {
//                       navigatePublicFun();
//                     }}
//                     className="upgrdbtn"
//                   >
//                     RENEWAL NOW <ArrowUpOutlined />
//                   </a>
//                 </span>
//                 ) : (
                    
//                 )
//               ) : AppExpDate?.RemainingDays < 1 ? (
//                 <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={() => {
//                       navigateFun();
//                     }}
//                     className="upgrdbtn"
//                   >
//                     RENEWAL NOW <ArrowUpOutlined />
//                   </a>
//                 </p>
//               ) : (
//                 <p>
//                   Your application subscription will expire within &nbsp;
//                   <span className="NosDays">
//                     {AppExpDate?.RemainingDays}
//                   </span>{' '}
//                   days. &nbsp;
//                   <a
//                     onClick={() => {
//                       navigateFun();
//                     }}
//                     className="upgrdbtn"
//                   >
//                     RENEWAL NOW <ArrowUpOutlined />
//                   </a>
//                 </p>
//               )}
//             </p>
//           </div>
//           {extendModel && (
//                 <ExtendSubscriptionModal  
//                         onClose={handleCancel}
//                         onPayNow={handlePay}
//                         onContinueWithCredits={freeExtend}
//                     /> 
//           )}
//          </>
//     )
// }
// export default PlanExpireNotification;
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 { getSession } from "../../../Services/Others";

const subDirectory = import.meta.env.BASE_URL;
const commonDirectory = import.meta.env.COMMON_BASE_URL;

const PlanExpireNotification = ({ ss }) => {
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const AppExpDate = useSelector(GlobalAppExpDateData);
  const SessionData = useSelector(StoredSessionData);
  const [extendModel, setExtendModel] = useState(false);
 const { AppId, UserId } = SessionData;
  console.log("AppExpDate", AppExpDate);

  // ================= NAVIGATION =================
  const navigateFun = () => {
    navigate(`${subDirectory}PricingPage`, { state: { AppName: SessionData?.AppName } });
  };

  const navigatePublicFun = () => {
    navigate(`${commonDirectory}`);
  };

  // ================= 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 isExtendExpired = useMemo(() => {
    return AppExpDate?.PlanType?.toLowerCase() === "extend expired";
  }, [AppExpDate]);

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

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

  // ================= FREE EXTEND =================
  const freeExtend = async () => {
    try {
     
      const now = new Date();y
      const currentDate = formatDate(now);

      const response1 = await dispatch(getPurchasedAppDetails({ AppId, UserId })).unwrap();
      const PurchasedDetails = response1?.data?.data;

      if (!PurchasedDetails?.length) return;

      const postData = {
        UserId,
        AppId,
        PricingId: PurchasedDetails[0]?.PricingId,
        PurDate: currentDate,
        NoofDays: 30,
        PaymentMode: 27,
        PaymentStatus: "S",
        LicenseStatus: PurchasedDetails[0]?.LicenseStatus,
        Price: PurchasedDetails[0]?.Price ?? 0,
        TaxId: PurchasedDetails[0]?.TaxId ?? 0,
        NetPrice: PurchasedDetails[0]?.ExistingPlanNetPrice ?? 0,
        ValidityStart: currentDate,
        ValidityEnd: addDays(currentDate, PurchasedDetails[0]?.NoOfDays),
        CreatedBy: UserId,
        TaxAmount: PurchasedDetails[0]?.TaxAmount ?? 0,
        MobileNo: getSession("MobileNo"),
        MailId: "ts@gmail.com",
        Type: "FreeExtend"
      };

      const response = await dispatch(postInvoice(postData)).unwrap();

      if (response?.data?.statusCode === 1 && response?.data?.SMSbody) {
        await dispatch(sendSms({ body: response.data.SMSbody }));
        setExtendModel(false);
      }

    } catch (error) {
      console.error("freeExtend error:", error);
    }
  };

  const handleCancel = () => {
    Logout();
    setExtendModel(false);
  };
 const Logout = async () => {
    const UserId = UserId;
    const status = 'N';
    try {
      const res = await dispatch(GenerateLogout({ UserId, status })).unwrap();
      if (res?.data?.statusCode === 1) {
        sessionStorage.clear();
        window.location.replace(`${commonSubDir}`);
      }
    } catch (error) {
      console.error('Logout failed:', error);
    }
  };
  const handlePay = () => {
    setExtendModel(false);
    navigate(`${subDirectory}PricingPage`, { state: { AppName: getSession("AppName") } });
  };

  // ================= UI BLOCKS =================
  const ExpiredBlock = () => (
    <span className="ExpiredMessage">
      Subscription expired &nbsp;
      <a onClick={navigatePublicFun} className="upgrdbtn">
        RENEWAL NOW <ArrowUpOutlined />
      </a>
    </span>
  );

  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={navigateFun} className="upgrdbtn">
        RENEWAL NOW <ArrowUpOutlined />
      </a>
    </p>
  );

  const ExpiringDaysBlock = () => (
    <p>
      Your application subscription will expire within &nbsp;
      <span className="NosDays">{AppExpDate?.RemainingDays}</span> days. &nbsp;
      <a onClick={navigateFun} className="upgrdbtn">
        RENEWAL NOW <ArrowUpOutlined />
      </a>
    </p>
  );

  // ================= RETURN =================
  return (
    <>
      <div className={ss}>
        {isExpired && isExtendExpired && <ExpiredBlock />}

        {isExpiringToday && <ExpiringTodayBlock />}

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

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

export default PlanExpireNotification;
