import { useEffect, useRef, useState, useContext } from "react";
import { Context } from "../../context/contex";
import Ads from "../../components/Ads";
import { formatLocalTime } from "../../utils/index";
import {

 IonPage,

 IonList,
 IonItem,
 IonRow,
 IonCol,
 IonText,
 IonGrid,
 IonLabel,
 IonCard,
 IonCardContent,
} from "@ionic/react";
import axios from "axios";
import AppShell from "../../components/Header";

const Alerts: React.FC = () => {
 const [alert, setAlert] = useState({
  notifications: [],
 });
 const context = useContext(Context);
 if (!context) {
  return <div>Loading...</div>;
 }

 const {
  apiURL,
  userInfo,
  validUser,
  
 } = context;

 const getAlert = async () => {
  if (!userInfo) return;

  try {
   const response = await axios.post(
    apiURL,
    new URLSearchParams({
     action: "get_user_notifications",
     email: userInfo.email,
    }),
    {
     headers: {
      "Content-Type": "application/x-www-form-urlencoded",
     },
    }
   );

   const data = response.data;

   if (data.error) {
    console.error("Error:", data.error);
   } else {
    setAlert(data);
    //  console.log("Fetched stat:", data);
   }
  } catch (error: any) {
   console.error("Error:", error?.message);
  }
 };

 useEffect(() => {
  getAlert();
  // console.log("LS", lastSlide);
 }, [userInfo]);

 const updateRead = async () => {
  if (!userInfo) return;

  try {
   const response = await axios.post(
    apiURL,
    new URLSearchParams({
     action: "update_read_notifications",
     email: userInfo.email,
    }),
    {
     headers: {
      "Content-Type": "application/x-www-form-urlencoded",
     },
    }
   );

   const data = response.data;

   if (data.error) {
    console.error("Error:", data.error);
   } else {
    //  console.log("Fetched stat:", data);
   }
  } catch (error: any) {
   console.error("Error:", error?.message);
  }
 };

 useEffect(() => {
  updateRead();
 }, []);

 return (
  <IonPage>
   <AppShell showBack={true} showLogo={false} title={'Notifications'}>
   {validUser && (
    <div className="">
     <IonGrid>
      {/* Title */}
      <IonRow className="ion-text-center ion-margin-vertical">
       <IonCol size="12">
        <h2>{userInfo?.first_name?.toUpperCase()}'s NOTIFICATIONS</h2>
       </IonCol>
      </IonRow>

      {/* Ads Section */}
      <IonRow className="ion-text-center ion-margin-vertical">
       <IonCol size="12">
        <Ads />
       </IonCol>
      </IonRow>

      {/* Notifications List */}
      {alert.notifications.length > 0 ? (
       <IonCard>
        <IonCardContent>
         <IonList>
          {alert.notifications.map((tx: any, index: number) => (
           <IonItem
            key={`tx_${index}`}
            lines="full"
            style={{ borderBottom: "1px dotted yellow" }}
           >
            <IonLabel>
             <h6>{tx.text}</h6>
             <IonText color="medium">
              <small>{formatLocalTime(tx.add_date)}</small>
             </IonText>
            </IonLabel>
           </IonItem>
          ))}
         </IonList>
        </IonCardContent>
       </IonCard>
      ) : (
       <IonRow className="ion-text-center ion-margin-vertical">
        <IonCol size="12">
         <img src="assets/images/fly.gif" height={80} alt="No data" />
         <p>No notifications found.</p>
        </IonCol>
       </IonRow>
      )}
     </IonGrid>
    </div>
   )}
   </AppShell>
  </IonPage>
 );
};

export default Alerts;
