import API_URL from "../../../config/api";
import styles from "./styles.module.css";
import { LuMail, LuMapPin, LuPhone } from "react-icons/lu";
import { CgSpinner } from "react-icons/cg";
import { useState } from "react";
import type { ApiErrorResponse } from "../../../types";
import { Navigate } from "react-router";
import AccordionFAQS from "../../../components/accordion FAQ´s/accordionFAQS";
import { motion } from "framer-motion";
import {
    pageTitleTransition,
    pageTitleVariants,
    slideFromBottomTransition,
    slideFromBottomVariants,
    slideFromLeftTransition,
    slideFromLeftVariants,
    slideFromRightTransition,
    slideFromRightVariants,
    viewportOnce,
} from "../../../utils/pageMotionVariants";

export default function Contactos() {
    const token = localStorage.getItem("token");

    if (!token) {
        return <Navigate to="/login" />;
    }
    
    const [error, setError] = useState<ApiErrorResponse | null>(null);
    const [sending, setSending] = useState<boolean>(false);
    const [messageSuccess, setMessageSuccess] = useState<string>("");

    async function sendMail(event: React.FormEvent<HTMLFormElement>) {
        event.preventDefault();
        const formElement = event.currentTarget;

        const formData = new FormData(formElement);
        const name = formData.get("name");
        const email = formData.get("email");
        const subject = formData.get("subject");
        const message = formData.get("message");

        const payload = {
            name: name,
            email: email,
            subject: subject,
            message: message,
        };

        setSending(true);
        const response = await fetch(`${API_URL}/api/contact`, {
            method: "POST",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
            body: JSON.stringify(payload),
        });

        const data = await response.json();

        if (response.ok) {
            setError(null);
            setSending(false);
            setMessageSuccess(data.message);
            setTimeout(() => {
                setMessageSuccess("");
            }, 3000)
            formElement.reset();
        } else {
            setError(data as ApiErrorResponse);
            setSending(false);
            setMessageSuccess("");
        }
    }    

        return (
            <div className={styles.container} >
                <motion.h1 variants={pageTitleVariants} initial="initial" animate="animate" transition={pageTitleTransition} className={styles.title}>Contactos</motion.h1>
                <div className="row">
                    <motion.div variants={slideFromLeftVariants} initial="initial" whileInView="animate" viewport={viewportOnce} transition={slideFromLeftTransition} className="col-12 col-lg-6 text-start d-flex flex-column gap-3 px-4 mt-3 mt-lg-0">
                        <div className="text-center text-sm-start">
                            <h2 className={styles.subtitle}>Os nossos dados</h2>
                            <span >Pode contactar-nos através do nosso email, telefone ou morada.</span>
                        </div>
                        <div className="d-flex flex-column gap-5 mt-4">
                            <a href="mailto:geral@livetech.pt" target="_blank" className={`${styles.contactBox} d-flex flex-column flex-sm-row gap-3 align-items-center p-4`}>
                                <LuMail className={styles.icon} size={30} />
                                <div className="d-flex flex-column text-center text-sm-start">
                                    <span className="text-black text-muted d-none d-sm-flex">Email</span>
                                    <span className={styles.contactData}>geral@livetech.pt</span></div>
                            </a>
                            <a href="tel:+351912345678" target="_blank" className={`${styles.contactBox} d-flex flex-column flex-sm-row gap-3 align-items-center p-4`}>
                                <LuPhone className={styles.icon} size={30} />
                                <div className="d-flex flex-column text-center text-sm-start">
                                    <span className="text-black text-muted d-none d-sm-flex">Telefone</span>
                                    <span className={styles.contactData}>+351 912 345 678</span></div>
                            </a>
                            <a href="https://maps.app.goo.gl/WQJBghKxshgPcs1v8" target="_blank" className={`${styles.contactBox} d-flex flex-column flex-sm-row gap-3 align-items-center p-4`}>
                                <LuMapPin className={styles.icon} size={30} />
                                <div className="d-flex flex-column text-center text-sm-start">
                                    <span className="text-black text-muted d-none d-sm-flex">Morada</span>
                                    <span className={styles.contactData}>Rua da Escola, 123, Lisboa, Portugal</span></div>
                            </a>
                        </div>
                    </motion.div>
                    <motion.div variants={slideFromRightVariants} initial="initial" whileInView="animate" viewport={viewportOnce} transition={slideFromRightTransition} className="col-12 col-lg-6 text-start d-flex flex-column gap-4 px-4 mt-5 mt-lg-0">
                        <div className="text-center text-sm-start">
                            <h2 className={styles.subtitle}>Formulário de contacto</h2>
                            <span>Preencha o formulário abaixo para entrar em contacto connosco</span>
                        </div>

                        <div className="mt-4">
                            <form onSubmit={sendMail} className="pt-2">
                                <div className="row g-3 bg-white p-4" style={{ borderRadius: "var(--border-radius)" }}>
                                    <div className="col-12 col-md-6 text-start mt-0">
                                        <label className={styles.label} htmlFor="name">Nome</label>
                                        <input type="text" className="form-control py-2 border" placeholder="Nome completo" id="name" name="name" />
                                    </div>
                                    <div className="col-12 col-md-6 text-start mt-0">
                                        <label className={styles.label} htmlFor="email">E-mail</label>
                                        <input type="email" placeholder="E-mail" className="form-control py-2 border" id="email" name="email" />
                                    </div>
                                    <div className="col-12 text-start">
                                        <label className={styles.label} htmlFor="subject">Assunto</label>
                                        <select className="form-select py-2 border" id="subject" name="subject" defaultValue="">
                                            <option value="" disabled>Assunto</option>
                                            <option value="Suporte Técnico" >Suporte Técnico</option>
                                            <option value="Sugestão">Sugestão</option>
                                            <option value="Dúvida">Dúvida</option>
                                            <option value="Outro">Outro</option>
                                        </select>
                                    </div>
                                    <div className="col-12 text-start">
                                        <label className={styles.label} htmlFor="message">Mensagem</label>
                                        <textarea rows={5} className="form-control border  py-2" id="message" name="message" placeholder="Escreva aqui a sua mensagem..." />
                                    </div>

                                    {error && (
                                        <div className="col-12 text-center">
                                            <span className="text-danger">{error.message}</span>
                                        </div>
                                    )}

                                    {messageSuccess && (
                                        <div className="col-12 text-center ">
                                            <span className="text-success">{messageSuccess}</span>
                                        </div>
                                    )}

                                    <div className="col-12 text-end">
                                        <button type="submit" className={`${styles.submitButton}`} disabled={sending}>{sending ? (<><span>A enviar...</span> <CgSpinner className={`${styles.animateSpin} mb-1`} size={20} /></>) : "Submeter"}</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </motion.div>

                    <motion.div variants={slideFromBottomVariants} initial="initial" whileInView="animate" viewport={viewportOnce} transition={slideFromBottomTransition} className="col-12 mt-5 text-center">
                        <span className={`${styles.title}`}>Perguntas Frequentes</span>
                        <div className="row mt-4">
                            <div className="col-12 mx-auto">
                                <AccordionFAQS />
                            </div>
                        </div>
                    </motion.div>
                </div>
            </div >
        );
    }