import React, { useState, useContext } from "react";
import {
 IonPage,
 IonHeader,
 IonToolbar,
 IonTitle,
 IonContent,
 IonCard,
 IonCardContent,
 IonItem,
 IonLabel,
 IonInput,
 IonTextarea,
 IonButton,
 IonIcon,
 IonText,
 IonList,
 IonButtons,
 IonBackButton,
 IonLoading,
} from "@ionic/react";
import {
 mailOutline,
 callOutline,
 logoFacebook,
 logoTwitter,
 logoInstagram,
 locationOutline,
 sendOutline,
 arrowBackOutline,
 alertCircle,
 checkmarkCircle,
 logoWhatsapp,
 logoYoutube,
} from "ionicons/icons";
import "./ContactUs.css";
import axios from "axios";

import { Context } from "../../context/contex";
const ContactUs: React.FC = () => {
 const context = useContext(Context);
 if (!context) {
  return <div>Loading...</div>;
 }

 const {
  apiURL,

  presentToast,

  busy,
  setBusy,
  settings,
 } = context;

 const [form, setForm] = useState({
  name: "",
  email: "",
  message: "",
 });

 const [loading, setLoading] = useState(false);

 const handleChange = (name: string, value: string | null | undefined) => {
  setForm((prev) => ({ ...prev, [name]: value || "" }));
 };

 const handleSubmit = async () => {
  if (!form.name || !form.email || !form.message) {
   presentToast(
    "top",
    `Please fill all fields`,
    () => null,
    "danger",
    alertCircle
   );
   return;
  }
  setBusy(true);

  try {
   const html = `
      <h3>New Contact Message</h3>
      <p><strong>Name:</strong> ${form.name}</p>
      <p><strong>Email:</strong> ${form.email}</p>
      <p><strong>Message:</strong></p>
      <p>${form.message}</p>
      <br/>
    `;
   const response = await axios.post(
    apiURL,
    new URLSearchParams({ action: "contact_us", html, name: form.name }),
    {
     headers: {
      "Content-Type": "application/x-www-form-urlencoded",
     },
    }
   );
   // console.log("Wallet data:", response.data);

   if (!response.data.success) {
    presentToast(
     "top",
     response.data.message,
     () => null,
     "danger",
     alertCircle
    );
   } else {
    setForm({ name: "", email: "", message: "" });
    presentToast(
     "top",
     response.data.message,
     () => null,
     "success",
     checkmarkCircle
    );
   }
  } catch (err) {
   presentToast(
    "top",
    "Failed to send message. Try again later.",
    () => null,
    "danger",
    alertCircle
   );
  } finally {
   setBusy(false);
  }
 };

 return (
  <IonPage>
   <IonHeader>
    <IonToolbar className="ion-padding-horizontal">
     <IonButtons slot="start">
      <IonBackButton
       text=""
       icon={arrowBackOutline}
       defaultHref="/"
      ></IonBackButton>
     </IonButtons>
     <IonTitle>Contact us</IonTitle>
    </IonToolbar>
   </IonHeader>
   <IonLoading
    isOpen={busy}
    message="Please wait..."
    spinner="circles"
    className="custom-loading"
   />
   <IonContent fullscreen className="ion-content-bg ion-padding">
    <IonCard className="contact-card">
     <IonCardContent>
      <h2 className="contact-heading">We’d love to hear from you!</h2>
      <IonText color="medium">
       <p>Fill out the form below or reach us via our channels.</p>
      </IonText>

      <IonList lines="none" className="contact-form">
       <IonItem style={{ border: "1px solid darkorange" }}>
        <IonInput
         label="Full Name"
         labelPlacement="floating"
         name="name"
         value={form.name}
         onIonInput={(e) => handleChange("name", e.detail.value)}
        />
       </IonItem>

       <IonItem style={{ border: "1px solid darkorange" }}>
        <IonInput
         label="Email Address"
         labelPlacement="floating"
         type="email"
         name="email"
         value={form.email}
         onIonInput={(e) => handleChange("email", e.detail.value)}
        />
       </IonItem>

       <IonItem style={{ border: "1px solid darkorange" }}>
        <IonTextarea
         label="Message"
         labelPlacement="floating"
         name="message"
         rows={12}
         value={form.message}
         onIonInput={(e) => handleChange("message", e.detail.value)}
        />
       </IonItem>

       <IonButton
        expand="block"
        color="primary"
        onClick={handleSubmit}
        disabled={loading}
        className="mt-3"
       >
        <IonIcon icon={sendOutline} slot="start" />
        {loading ? "Sending..." : "Send Message"}
       </IonButton>
      </IonList>
     </IonCardContent>
    </IonCard>

    <IonCard className="contact-info-card">
     <IonCardContent>
      <h3>Contact Information</h3>
      <IonItem lines="none">
       <IonIcon icon={callOutline} slot="start" />
       <IonLabel>{settings?.contact_phone}</IonLabel>
      </IonItem>

      <IonItem lines="none">
       <IonIcon icon={mailOutline} slot="start" />
       <IonLabel>{settings?.contact_email}</IonLabel>
      </IonItem>

      <IonItem lines="none">
       <IonIcon icon={locationOutline} slot="start" />
       <IonLabel>{settings?.contact_address}</IonLabel>
      </IonItem>

      <div className="social-icons">
       {settings?.facebook && (
        <IonButton fill="clear" href={settings?.facebook} target="_blank">
         <IonIcon icon={logoFacebook} />
        </IonButton>
       )}
       {settings?.x && (
        <IonButton fill="clear" href={settings?.x} target="_blank">
         <IonIcon icon={logoTwitter} />
        </IonButton>
       )}
       {settings?.instagram && (
        <IonButton fill="clear" href={settings?.instagram} target="_blank">
         <IonIcon icon={logoInstagram} />
        </IonButton>
       )}
       {settings?.whatsapp && (
        <IonButton fill="clear" href={settings.whatsapp} target="_blank">
         <IonIcon icon={logoWhatsapp} />
        </IonButton>
       )}

       {settings?.youtube && (
        <IonButton fill="clear" href={settings.youtube} target="_blank">
         <IonIcon icon={logoYoutube} />
        </IonButton>
       )}
      </div>
     </IonCardContent>
    </IonCard>
   </IonContent>
  </IonPage>
 );
};

export default ContactUs;
