'use client';

import React, { useState } from "react";
import { IoMdCloseCircleOutline } from "react-icons/io";
import { useWebContext } from "@/app/(site)/providers";
import { toast } from "react-toastify";
import { API_URL, TOKEN } from "@/utils/constants/selectConstants";
import { inputMask, onlyNumbers } from "@/utils/functions";

import Image from "next/image";
import exclusiveOffer from "../../../../../public/assets/Images/ImageLPCaixa/logo-plamev-caixa-popup.svg";
import presenteCaixa from "../../../../../public/assets/Images/ImageLPCaixa/presenteCaixa.svg";
import Heart from "../../../../../public/assets/Images/ImageLPCaixa/Heart.svg";

import sanitizeHtml from "sanitize-html";
import Link from "next/link";

interface INovoLeadSite {
    Nome: string;
    Ddd: string;
    Telefone: string;
    OrigensId: string;
    LeadsPets: LeadsPet[];
    ConsultoresId?: string;
}

interface LeadsPet {
    NomePet: string;
}

const ModalGarantirDesconto = () => {
    const { setIsModalStateOpenLPCaixa, isModalStateOpenLPCaixa, nomeLeadDesconto, setNomeLeadDesconto, telefoneLeadDesconto, setTelefoneLeadDesconto, nomePetLeadDesconto, setNomePetLeadDesconto } = useWebContext();
    const [garantirDesconto, setGarantirDesconto] = useState(false);

    async function getLeads() {
        let formData = {} as INovoLeadSite;

        if (!sanitizeHtml(nomeLeadDesconto) || !sanitizeHtml(telefoneLeadDesconto) || !sanitizeHtml(nomePetLeadDesconto)) {
            toast.error('Preencha os campos obrigatórios corretamente.');
            return;
        }

        formData.Nome = sanitizeHtml(nomeLeadDesconto);
        formData.Ddd = onlyNumbers(telefoneLeadDesconto).substring(0, 2);
        formData.Telefone = onlyNumbers(telefoneLeadDesconto).substring(2);
        formData.OrigensId = "CEFColaboradores";
        formData.ConsultoresId = "plamev";

        formData.LeadsPets = [{ NomePet: sanitizeHtml(nomePetLeadDesconto) }];

        try {
            const res = await fetch(`${API_URL}Leads/NovoLeadSite/`, {
                method: 'POST',
                headers: {
                    Authorization: TOKEN,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });

            const body = await res.json();

            if (body.erro) {
                toast.error(body.mensagem);
                return;
            }

            toast.success("Desconto garantido com sucesso!");
            setGarantirDesconto(true);
        } catch (err) {
            toast.error("Erro ao enviar, tente novamente.");
        }
    }

    return (
        <>
            {isModalStateOpenLPCaixa && (
                <div
                    className="h-full w-full fixed top-0 z-[9999999] bg-zinc-900/[.70] flex justify-center items-center"
                    onClick={() => setIsModalStateOpenLPCaixa(false)}
                >
                    <div
                        className="w-full max-w-[552px] min-h-[575px] mx-4 sm:mx-0"
                        onClick={e => e.stopPropagation()}
                    >
                        <div className="flex justify-end items-center mb-5">
                            <div
                                className="text-white font-thin text-[32px] cursor-pointer"
                                onClick={() => setIsModalStateOpenLPCaixa(false)}
                            >
                                <IoMdCloseCircleOutline />
                            </div>
                        </div>

                        <div className="bg-[#FEFAEA] flex flex-col justify-between items-center px-2 py-5 rounded-[20px]">
                            <Image src={exclusiveOffer} alt="" width={180} height={47} />

                            {!garantirDesconto ? (
                                <>
                                    <h5 className="text-[32px] text-center leading-[32px] text-[#0C4451] font-semibold mt-5">
                                        Preencha as informações{" "}
                                        <span className="text-plamev-blue-500">para resgatar</span>{" "}
                                        <span className="inline-flex items-center">
                                            seu desconto.
                                            <Image src={Heart} alt="" width={24} height={23} className="ml-1" />
                                        </span>
                                    </h5>

                                    <input
                                        name="Nome"
                                        type="text"
                                        placeholder="Nome"
                                        value={nomeLeadDesconto}
                                        onChange={(e) => setNomeLeadDesconto(e.target.value)}
                                        className="w-full max-w-[434px] h-[52px] px-4 py-2 border border-[#eff0ed] rounded-md focus:outline-none focus:ring-2 focus:[#eff0ed] mt-5"
                                    />

                                    <input
                                        type="text"
                                        placeholder="Telefone de Contato"
                                        maxLength={15}
                                        value={inputMask(telefoneLeadDesconto, 'telefone')}
                                        onChange={({ target }) => setTelefoneLeadDesconto(target.value)}
                                        className="w-full max-w-[434px] h-[52px] px-4 py-2 border border-[#eff0ed] rounded-md focus:outline-none focus:ring-2 focus:[#eff0ed] mt-5"
                                    />

                                    <input
                                        name="NomePet"
                                        type="text"
                                        placeholder="Nome do Pet"
                                        value={nomePetLeadDesconto}
                                        onChange={(e) => setNomePetLeadDesconto(e.target.value)}
                                        className="w-full max-w-[434px] h-[52px] px-4 py-2 border border-[#eff0ed] rounded-md focus:outline-none focus:ring-2 focus:[#eff0ed] mt-5"
                                    />

                                    <button
                                        onClick={getLeads}
                                        className="w-full max-w-[434px] h-[76px] bg-[#E8AB3A] border-4 border-[#F3D086] rounded-xl text-[#4B3A17] font-semibold text-lg flex items-center justify-center hover:brightness-110 transition mt-5"
                                    >
                                        Garantir desconto agora
                                    </button>
                                </>
                            ) : (
                                <>
                                    <h5 className="text-[32px] text-center leading-[32px] text-[#0C4451] font-semibold mt-5">
                                        Seu desconto exclusivo{" "}
                                        <span className="text-plamev-blue-500 inline-flex items-center">
                                            foi aplicado com sucesso.
                                            <Image src={Heart} alt="" width={24} height={23} className="ml-1" />
                                        </span>
                                    </h5>

                                    <Image src={presenteCaixa} alt="" width={164} height={114} className="mt-10 mb-10" />

                                    <Link
                                        href="/planos?plano=4&origem=caixa&consultor=caixaeconomica"
                                        onClick={() => setIsModalStateOpenLPCaixa(false)}
                                        className="w-full max-w-[434px] h-[76px] bg-[#E8AB3A] border-4 border-[#F3D086] rounded-xl text-[#4B3A17] font-semibold text-lg flex items-center justify-center hover:brightness-110 transition mt-5"
                                    >
                                        Proteger meu pet agora
                                    </Link>
                                </>
                            )}
                        </div>
                    </div>
                </div>
            )}
        </>
    );
};

export default ModalGarantirDesconto;