'use client'

import EtapaCheckout from "../_components/EtapaCheckout";
import Plan from "./_components/Plan";

import { useCallback, useEffect, useRef, useState } from "react";
import { useSearchParams } from "next/navigation";
import { useCheckoutContext } from "@/hooks/UseCheckout";
import { useWebContext } from "@/app/(site)/providers";
import { API_URL, TOKEN } from "@/utils/constants/selectConstants";
import { ICheckoutPets } from "@/utils/Interfaces/ICheckoutContext";
import { toast } from "react-toastify";
import { pad } from "@/utils/functions";
import { useRouter } from "next/navigation";

import IconArrowRight from "../../../../public/assets/Images/Icons/arrow_icons.svg";
import IconClose from "../../../../public/assets/Images/Icons/iconClose.svg"
import Image from "next/image";
import PlanCardNewTable from "./_components/PlanNew";

const Page = () => {
    const searchParams = useSearchParams();
    const router = useRouter();

    const tipoCoberturasId = searchParams.get("plano");
    const consultor = searchParams.get("consultor")
    const origem = searchParams.get("origem")
    const cupomDesconto = searchParams.get("cupom")

    const { newComparePlans, isMobile, nomePetLeadDesconto } = useWebContext();
    const { setStep, setPlanId, setPlanTypeId, setConsultantId, pets, setPets, planId, planName, setPlanName, setConsultantPhone } = useCheckoutContext();

    const [plan, setPlan] = useState<string | null>(null);
    const [name, setName] = useState<string>(nomePetLeadDesconto || '');
    const [idadeAproximada, setIdadeAproximada] = useState<string>('');
    const [openDropdownIndex, setOpenDropdownIndex] = useState<number | null>(null);

    const [typePlan, setTypePlan] = useState<string>('');
    const [especie, setEspecie] = useState<string>('');
    const [campanhasCoberturasId, setCampanhasCoberturasId] = useState<string | undefined>(undefined);
    const [campanhasCoberturasTabelasId, setCampanhasCoberturasTabelasId] = useState<string | undefined>(undefined);

    const carouselRef = useRef<HTMLDivElement>(null);
    const [canScrollLeft, setCanScrollLeft] = useState(false);
    const [canScrollRight, setCanScrollRight] = useState(false);

    const updateScrollButtons = useCallback(() => {
        const el = carouselRef.current;
        if (!el) return;
        setCanScrollLeft(el.scrollLeft > 0);
        setCanScrollRight(el.scrollLeft + el.clientWidth < el.scrollWidth - 1);
    }, []);

    const getCardScrollStep = () => {
        const el = carouselRef.current;
        if (!el) return 340;

        const firstCard = el.querySelector<HTMLElement>('[data-plan-card]');
        if (!firstCard) return 340;

        return Math.round(firstCard.getBoundingClientRect().width);
    };

    const handleScrollLeft = () => {
        const step = getCardScrollStep();
        carouselRef.current?.scrollBy({ left: -step, behavior: 'smooth' });
    };

    const handleScrollRight = () => {
        const step = getCardScrollStep();
        carouselRef.current?.scrollBy({ left: step, behavior: 'smooth' });
    };

    useEffect(() => {
        setStep(1);
        const searchEspecie = searchParams.get("Especie");
        setEspecie(searchEspecie ? searchEspecie.toUpperCase() : '');
    }, [searchParams, setStep]);

    function getConsultantsData(login: string) {
        fetch(`${API_URL}Consultores/ConsultarLogin/${login}`, {
            headers: { Authorization: TOKEN }
        })
            .then(res => res.json())
            .then(body => { setConsultantId(body.Id), setConsultantPhone(body.Ddd + body.Telefone) })
            .catch(error => console.error("Erro na requisição:", error));
    }

    useEffect(() => {
        if (tipoCoberturasId) {
            fetch(`${API_URL}Coberturas/VerificarCoberturasPorTiposCoberturas/${tipoCoberturasId}`, {
                headers: { Authorization: TOKEN }
            })
                .then(res => res.json())
                .then(body => {
                    setPlan(body.Valido ? tipoCoberturasId : null);
                })
                .catch(error => console.error("Erro na requisição:", error));
        } else {
            setPlan(null);
            setPlanId('');
            setPlanTypeId('');
            setPlanName('');
        }
        if (consultor) getConsultantsData(consultor);
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [tipoCoberturasId, consultor]);

    const handleAddPet = () => {
        let listPets = pets;
        let pet = {} as ICheckoutPets;

        if (!name) {
            toast.error('O nome do pet é obrigatório');
            return;
        }

        if (!especie) {
            toast.error('A espécie do pet é obrigatória');
            return;
        }

        pet.NomePet = name;
        pet.CoberturasId = planId ?? '';
        pet.TiposCoberturasId = plan ?? '';
        pet.CoberturasNome = planName;
        pet.Especie = especie;
        if (campanhasCoberturasId) pet.CampanhasCoberturasId = campanhasCoberturasId;
        if (campanhasCoberturasTabelasId) pet.CampanhasCoberturasTabelasId = campanhasCoberturasTabelasId;

        listPets.push({ ...pet });

        setPets([...listPets]);
        setName('')
        setTypePlan('')

        toast.success('Pet adicionado com sucesso.');
    }

    const handleRemovePet = (position: number) => {
        let listPets = pets;
        listPets.splice(position, 1);
        setPets([...listPets]);
        toast.success('Pet removido com sucesso.');
    }

    const isPlanCompatible = (item: any, checkEspecie: string = especie) => {
        if (!checkEspecie || checkEspecie === "TODOS") return true;

        let planEspecieStr = "TODOS";
        const pEspecie = item.Especie || item.Valores?.[0]?.PlanosEspecie;
        const nomeUpper = item.TiposCoberturasNome.toUpperCase();

        if (pEspecie === "1" || String(pEspecie).toUpperCase() === "CANINO" || nomeUpper.includes("CANINO") || nomeUpper.includes("CACHORRO")) {
            planEspecieStr = "CANINO";
        } else if (pEspecie === "2" || String(pEspecie).toUpperCase() === "FELINO" || nomeUpper.includes("FELINO") || nomeUpper.includes("GATO")) {
            planEspecieStr = "FELINO";
        }

        if (checkEspecie === "CANINO" && planEspecieStr === "FELINO") return false;
        if (checkEspecie === "FELINO" && planEspecieStr === "CANINO") return false;

        return true;
    };

    const handleEspecieChange = (newEspecie: string) => {
        setEspecie(newEspecie);

        // Copia todos os params originais da URL (preserva plano, origem, consultor, etc.)
        const params = new URLSearchParams(searchParams.toString());

        if (!newEspecie) {
            params.delete('Especie');
            params.delete('plano');
            setPlan(null);
            setPlanId('');
            setPlanTypeId('');
            setPlanName('');
            const qs = params.toString();
            router.push(`/planos${qs ? `?${qs}` : ''}`);
            return;
        }

        params.set('Especie', newEspecie);

        if (plan && newEspecie) {
            const selectedPlanDetails = newComparePlans?.Coberturas?.find((p: any) => p.TiposCoberturasId === plan);
            if (selectedPlanDetails) {
                if (!isPlanCompatible(selectedPlanDetails, newEspecie)) {
                    toast.warning('O plano selecionado não é compatível com a espécie escolhida. Por favor, selecione outro plano.');
                    setPlan(null);
                    setPlanId('');
                    setPlanTypeId('');
                    setPlanName('');
                    params.delete('plano');
                    router.push(`/planos?${params.toString()}`);
                    return;
                }
            }
        }

        router.push(`/planos?${params.toString()}`);
    }

    const handleSelectPlan = (coberturasId: string, tipoCoberturasId: string, coberturasNome: string, planEspecie?: string, newCampanhasCoberturasId?: string, newCampanhasCoberturasTabelasId?: string) => {
        let currentEspecie = searchParams.get("Especie") || especie;

        if (planEspecie) {
            if (planEspecie === "1" || planEspecie.toUpperCase() === "CANINO") { currentEspecie = "CANINO"; setEspecie("CANINO"); }
            else if (planEspecie === "2" || planEspecie.toUpperCase() === "FELINO") { currentEspecie = "FELINO"; setEspecie("FELINO"); }
            // TODOS: mantém a espécie já selecionada pelo usuário, não sobrescreve
        } else if (coberturasNome) {
            const nomeUpper = coberturasNome.toUpperCase();
            if (nomeUpper.includes('FELINO') || nomeUpper.includes('GATO')) { currentEspecie = 'FELINO'; setEspecie('FELINO'); }
            else if (nomeUpper.includes('CANINO') || nomeUpper.includes('CACHORRO')) { currentEspecie = 'CANINO'; setEspecie('CANINO'); }
        }

        // Copia todos os params originais e atualiza apenas plano e Especie
        const params = new URLSearchParams(searchParams.toString());
        if (tipoCoberturasId) params.set('plano', tipoCoberturasId);
        else params.delete('plano');
        if (currentEspecie && currentEspecie !== 'TODOS') params.set('Especie', currentEspecie);
        else params.delete('Especie');

        router.push(`/planos?${params.toString()}`);
        setPlan(tipoCoberturasId);
        setPlanId(coberturasId);
        setPlanTypeId(tipoCoberturasId);
        setPlanName(coberturasNome);
        setCampanhasCoberturasId(newCampanhasCoberturasId);
        setCampanhasCoberturasTabelasId(newCampanhasCoberturasTabelasId);
    }

    useEffect(() => {
        if (!plan || !newComparePlans?.Coberturas) return;

        const matchingPlan = newComparePlans.Coberturas.find((item: any) => {
            if (item.TiposCoberturasId !== plan) return false;
            if (origem === "caixa") return item.OrigemCheckout === "CAIXA";
            if (origem === "lp") return item.OrigemCheckout === "LP";
            return item.OrigemCheckout === "SITE";
        });

        if (matchingPlan) {
            setPlanId(matchingPlan.Id);
            setPlanTypeId(matchingPlan.TiposCoberturasId);
            setPlanName(matchingPlan.TiposCoberturasNome);

            if (matchingPlan?.Cartao?.Composicao?.Pets?.[0]) {
                const campId = matchingPlan.Cartao.Composicao.Pets[0].CampanhasCoberturasId;
                const campTabelaId = matchingPlan.Cartao.Composicao.Pets[0].CampanhasCoberturasTabelasId;
                setCampanhasCoberturasId(campId || undefined);
                setCampanhasCoberturasTabelasId(campTabelaId || undefined);
            }
        }
    }, [plan, newComparePlans?.Coberturas, origem, setPlanId, setPlanTypeId, setPlanName]);

    useEffect(() => {
        const el = carouselRef.current;
        if (!el) return;
        updateScrollButtons();
        el.addEventListener('scroll', updateScrollButtons);
        window.addEventListener('resize', updateScrollButtons);
        return () => {
            el.removeEventListener('scroll', updateScrollButtons);
            window.removeEventListener('resize', updateScrollButtons);
        };
    }, [updateScrollButtons, newComparePlans?.Coberturas?.length, origem, isMobile, plan]);

    const sortedPlans = isMobile && Array.isArray(newComparePlans?.Coberturas) ? newComparePlans.Coberturas.sort((a, b) => { return a.TiposCoberturasId === plan ? -1 : b.TiposCoberturasId === plan ? 1 : 0; }) : newComparePlans?.Coberturas ?? [];
    const hasEspecieFilter = !!especie && especie !== "TODOS";

    const defaultPlanIds = ["17", "4", "5", "18"];

    const seenDefaultPlans = new Set<string>();
    const filteredPlans = sortedPlans.filter(item => {
        if (!isPlanCompatible(item)) return false;

        if (origem === "caixa") return item.OrigemCheckout === "CAIXA";
        if (origem === "lp") return item.OrigemCheckout === "LP";

        if (plan) return item.TiposCoberturasId === plan;

        // Sem espécie selecionada: exibe o conjunto padrão de planos (todos, sem filtro de origem)
        if (!especie) {
            if (!defaultPlanIds.includes(item.TiposCoberturasId)) return false;
            if (seenDefaultPlans.has(item.TiposCoberturasId)) return false;
            seenDefaultPlans.add(item.TiposCoberturasId);
            return true;
        }

        return item.OrigemCheckout === "SITE";
    });

    const showComparison =
        newComparePlans?.Coberturas &&
        (filteredPlans.length === 1 || (plan && filteredPlans.length > 0));

    return (
        <>
            <EtapaCheckout etapa={1} />

            <div className={`flex flex-col justify-center md:flex-row ${origem === "caixa" ? 'mt-10' : 'items-center'}  px-4 md:px-8 mt-[10px] gap-6`}>
                <div className="w-full md:max-w-[279px] md:flex-shrink-0 pr-0 md:pr-[16px]">
                    <h2 className="m-0 p-0 text-plamev-blue-500 mt-[-10px] text-[32px] mb-[40px]">Dados do pet</h2>

                    <input
                        type="text"
                        placeholder="Qual o nome do seu pet"
                        value={name}
                        onChange={({ target }) => setName(target.value)}
                        className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2 mb-4"
                        disabled={origem === 'lp' && pets.length == 1}
                        readOnly={origem === 'lp' && pets.length == 1}
                    />

                    <select
                        value={especie}
                        onChange={({ target }) => handleEspecieChange(target.value)}
                        className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2 mt-[16px] text-plamev-dark-400 mb-4"
                        disabled={origem === 'lp' && pets.length == 1}
                    >
                        <option value="">Selecione a espécie</option>
                        <option value="FELINO">Felino</option>
                        <option value="CANINO">Canino</option>
                    </select>

                    <button
                        disabled={(origem === 'lp' && pets.length == 1) || !planId}
                        type="button"
                        onClick={() => handleAddPet()}
                        className={` ${!planId ? 'bg-plamev-blue-200' : 'bg-plamev-blue-500'} text-white rounded-md h-[56px] w-full flex items-center justify-between px-[16px]`}
                    >
                        Adicionar pet <Image src={IconArrowRight} alt="Adicionar PET" />
                    </button>

                    {pets.length > 0 &&
                        <>
                            <h2 className="m-0 p-0 text-plamev-dark-400 font-bold text-[18px] mt-[16px] mb-[16px]">Pets adicionados</h2>

                            <div className="flex flex-col gap-3 max-h-[150px] overflow-y-scroll">
                                {pets.map((item, key: number) => (
                                    <div className="flex justify-between items-center w-full" key={key}>
                                        <div className="bg-plamev-green-500 border-2 border-plamev-green-600 w-[50px] h-[52px] flex justify-center items-center rounded-l-md">
                                            <p className="m-0 p-0 text-plamev-green-900">{pad(String(key + 1), 2, '')}</p>
                                        </div>
                                        <div className="bg-plamev-light-100 border-2 border-plamev-yellow-100 w-[100%] h-[52px] flex justify-between items-center border-l-0 rounded-r-md px-[16px]">
                                            <div>
                                                <p className="m-0 p-0 text-plamev-dark-500">{item.NomePet}</p>
                                                <p className="m-0 p-0 text-plamev-yellow-500 text-sm">{item.CoberturasNome}</p>
                                            </div>
                                            <div className="relative">
                                                <button
                                                    type="button"
                                                    title="Remover pet"
                                                    className="border-0 w-[20px] h-[20px] flex justify-center items-center"
                                                    onClick={() => handleRemovePet(key)}
                                                >
                                                    <Image src={IconClose} width={15} alt="Menu pet" />
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </>
                    }

                    {origem === 'caixa' && !isMobile &&
                        <div className="flex justify-center sm:justify-start mt-4">
                            <iframe
                                className="rounded-lg"
                                width="151.32"
                                height="85.17"
                                src={`https://www.youtube.com/embed/4uAQHwYa-Rk?autoplay=1&mute=1&playsinline=1&controls=1&modestbranding=1&rel=0`} // Adiciona mute=1 para silenciar
                                title="YouTube video player"
                                frameBorder="0"
                                allow="autoplay; encrypted-media; picture-in-picture"
                                allowFullScreen
                            />
                        </div>
                    }
                </div>

                <div className="border-dashed border-plamev-yellow-100 h-[400px] mr-[-10px] border-l-2 hidden sm:block"></div>

                <div className={`w-[100%] md:w-[1024px] flex flex-col justify-start md:pl-[16px] overflow-hidden`}>
                    {origem !== 'caixa' &&
                        <>
                            <h2 className="m-0 p-0 text-start leading-[32px] text-plamev-blue-500  text-[32px] pl-[10px] pt-[60px]">Escolha o melhor plano para o seu pet</h2>
                        </>
                    }

                    {showComparison ? (
                        <>
                            <div className="flex justify-start w-full">
                                <div className="max-w-[324px] w-full mt-[52px] mb-[24px]">
                                    {origem === 'caixa' ? (
                                        <PlanCardNewTable
                                            title={filteredPlans[0].TiposCoberturasNome}
                                            coberturasId={filteredPlans[0].Id}
                                            tipoCoberturasId={filteredPlans[0].TiposCoberturasId}
                                            selected={filteredPlans[0].TiposCoberturasId === plan}
                                            dados={filteredPlans[0]}
                                            openDropdownIndex={openDropdownIndex}
                                            setOpenDropdownIndex={(item) => setOpenDropdownIndex(item)}
                                            selectPlan={(coberturasId: string, tipoCoberturasId: string, title: string) =>
                                                handleSelectPlan(coberturasId, tipoCoberturasId, title, filteredPlans[0].Especie || filteredPlans[0].Valores?.[0]?.PlanosEspecie)
                                            }
                                        />
                                    ) : (
                                        <Plan
                                            title={filteredPlans[0].TiposCoberturasNome}
                                            price={filteredPlans[0].Cartao.Composicao.ValorComDesconto}
                                            originalPrice={filteredPlans[0].Cartao.Composicao.ValorMensalidade}
                                            coberturasId={filteredPlans[0].Id}
                                            selected={filteredPlans[0].TiposCoberturasId === plan}
                                            tipoCoberturasId={filteredPlans[0].TiposCoberturasId}
                                            coberturasNome={filteredPlans[0].TiposCoberturasNome}
                                            exibirSite={filteredPlans[0].Cartao.Composicao.CampanhasCoberturasExibeSite}
                                            selectPlan={(coberturasId: string, tipoCoberturasId: string, title: string) =>
                                                handleSelectPlan(coberturasId, tipoCoberturasId, title, filteredPlans[0].Especie || filteredPlans[0].Valores?.[0]?.PlanosEspecie, filteredPlans[0].Cartao.Composicao.Pets[0].CampanhasCoberturasId, filteredPlans[0].Cartao.Composicao.Pets[0].CampanhasCoberturasTabelasId)
                                            }
                                        />
                                    )}
                                </div>
                            </div>
                        </>
                    ) : (
                        <div className="relative">
                            {canScrollLeft && (
                                <button
                                    type="button"
                                    onClick={handleScrollLeft}
                                    className="absolute left-0 top-1/2 -translate-y-1/2 z-10 bg-plamev-blue-500 hover:bg-plamev-blue-600 text-white w-10 h-10 rounded-full flex items-center justify-center shadow-md transition-all duration-200"
                                    title="Plano anterior"
                                >
                                    <svg xmlns="http://www.w3.org/2000/svg" className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
                                    </svg>
                                </button>
                            )}

                            <div className="embla">
                                <div
                                    ref={carouselRef}
                                    className="embla__container overflow-x-hidden overflow-y-hidden pb-2 mb-2 snap-x snap-mandatory"
                                >
                                    {filteredPlans.map((item, key) => (
                                        <div
                                            className={`flex-none w-[85vw] ${
                                                origem === "caixa" ? "max-w-[335px]" : "max-w-[340px]"
                                            } px-3 pt-[50px] snap-start`}
                                            data-plan-card
                                            key={key}
                                        >
                                            {origem === "caixa" ? (
                                                <PlanCardNewTable
                                                    title={item.TiposCoberturasNome}
                                                    coberturasId={item.Id}
                                                    tipoCoberturasId={item.TiposCoberturasId}
                                                    selected={item.TiposCoberturasId === plan}
                                                    dados={item}
                                                    openDropdownIndex={openDropdownIndex}
                                                    setOpenDropdownIndex={(item) => setOpenDropdownIndex(item)}
                                                    selectPlan={(
                                                        coberturasId: string,
                                                        tipoCoberturasId: string,
                                                        title: string
                                                    ) =>
                                                        handleSelectPlan(
                                                            coberturasId,
                                                            tipoCoberturasId,
                                                            title,
                                                            item.Especie || item.Valores?.[0]?.PlanosEspecie
                                                        )
                                                    }
                                                />
                                            ) : (
                                                <Plan
                                                    title={item.TiposCoberturasNome}
                                                    price={item.Cartao.Composicao.ValorComDesconto}
                                                    originalPrice={item.Cartao.Composicao.ValorMensalidade}
                                                    coberturasId={item.Id}
                                                    selected={item.TiposCoberturasId === plan}
                                                    tipoCoberturasId={item.TiposCoberturasId}
                                                    coberturasNome={item.TiposCoberturasNome}
                                                    exibirSite={item.Cartao.Composicao.CampanhasCoberturasExibeSite}
                                                    selectPlan={(
                                                        coberturasId: string,
                                                        tipoCoberturasId: string,
                                                        title: string
                                                    ) =>
                                                        handleSelectPlan(
                                                            coberturasId,
                                                            tipoCoberturasId,
                                                            title,
                                                            item.Especie || item.Valores?.[0]?.PlanosEspecie,
                                                            item.Cartao?.Composicao?.Pets?.[0]?.CampanhasCoberturasId,
                                                            item.Cartao?.Composicao?.Pets?.[0]?.CampanhasCoberturasTabelasId
                                                        )
                                                    }
                                                />
                                            )}
                                        </div>
                                    ))}
                                </div>
                            </div>

                            {canScrollRight && (
                                <button
                                    type="button"
                                    onClick={handleScrollRight}
                                    className="absolute right-0 top-1/2 -translate-y-1/2 z-10 bg-plamev-blue-500 hover:bg-plamev-blue-600 text-white w-10 h-10 rounded-full flex items-center justify-center shadow-md transition-all duration-200"
                                    title="Próximo plano"
                                >
                                    <svg xmlns="http://www.w3.org/2000/svg" className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
                                    </svg>
                                </button>
                            )}
                        </div>
                    )}
                </div>
            </div>

            {origem === 'caixa' && isMobile &&
                <div className="flex justify-start p-2 mb-32">
                    <iframe
                        className="rounded-lg"
                        width="237.28"
                        height="140.4"
                        src={`https://www.youtube.com/embed/4uAQHwYa-Rk?autoplay=1&mute=1&playsinline=1&controls=1&modestbranding=1&rel=0`} // Adiciona mute=1 para silenciar
                        title="YouTube video player"
                        frameBorder="0"
                        allow="autoplay; encrypted-media; picture-in-picture"
                        allowFullScreen
                    />
                </div>
            }
        </>
    )
}

export default Page;