'use client'

import { createContext, useContext, useEffect, useState, Dispatch, SetStateAction } from 'react';
import { getInitDataAccredited } from '@/actions/hooksActionsAccredited';
import { toast } from 'react-toastify';
import { interfaceBuscarCredenciadosFiltros } from '@/utils/Interfaces/interfaceBuscarCredenciadosFiltros';
import { Jobs } from "@/utils/Interfaces/interfaceTrabalheConosco";
import { API_URL, TOKEN } from '@/utils/constants/selectConstants';
import { set } from 'zod';
import { ViewSitePosts, ViewSitePostsMaisAcessados } from '@/utils/Interfaces/interfaces';

interface ISearchCredentialPerState {
    laboratory?: boolean,
    neighborhood?: string,
    plantation?: boolean,
    statesId?: string,
    cityesId?: string,
    specialityId?: string 
}

interface IPosition {
    lat: number;
    lng: number;
}

interface ICredentialContext {
    searchCredentialPerState: (params: ISearchCredentialPerState) => Promise<void>;
    getCenter: any[];
    getZoom: number;
    addressStores: interfaceBuscarCredenciadosFiltros[];
    openModalIndicatio: boolean;
    setOpenModalIndication: (isOPen: boolean) => void;
    setSearchData: (search: string) => void;
    searchData: string;
    setCenter: (position: IPosition[]) => void;
    setStates: (states: string) => void;
    setCityes: (citys: string) => void;
    states: string;
    cityes: string;
    openMap: boolean;
    setopenmap(openMap: boolean): void;
    setModalOpen(openModalFilter: boolean): void;
    isModalOpen: boolean;
    setStatesId: (statesId: string) => void;
    setCityesId: (cityesId: string) => void;
    setNeighborhood: (neighborhood: string) => void;
    setLaboratory: (laboratory: boolean | undefined) => void;
    setPlantation: (plantation: boolean | undefined) => void;
    statesId: string;
    cityesId: string
    neighborhood: string;
    laboratory: boolean | undefined;
    plantation: boolean | undefined;
    closeMenu: boolean;
    setCloseMenu(close: boolean): void;
    modalDepoimentos: string;
    setModalDepoimentos(depoimento: string): void;
    modalComunicado: boolean;
    setModalComunicado(comunicado: boolean): void;
    job: Jobs;
    setJob(job: Jobs): void;
    adesoes: IAdesoes[];
    setAdesoes(adesoes: IAdesoes[]): void;
    setPostMaisRecente(post: ViewSitePosts | undefined): void;
    postMaisRecente: ViewSitePosts | undefined;
    setPostMaisAcessados: Dispatch<SetStateAction<ViewSitePostsMaisAcessados[] | undefined>>;
    postMaisAcessados: ViewSitePostsMaisAcessados[] | undefined;
    setPostContinueLendo: Dispatch<SetStateAction<ViewSitePostsMaisAcessados[] | undefined>>;
    postMaisContinueLendo: ViewSitePostsMaisAcessados[] | undefined;
    specialityId: string;
    setSpecialityId(specialityId: string): void;
    specialityNome: string;
    setSpecialityNome(specialityNome: string): void;
}

export interface IAdesoes {
    Total: string
    ClientesNome: string
    PlanosNome: string
    IndividuosEnderecosCidadesNome: string
    IndividuosEnderecosEstadosUF: string
    VendasDataCadastro: string
    PetsNome: string
    PetsEspecie: string
}


const CredentialContext = createContext<ICredentialContext>({} as ICredentialContext);

export default function ProvidersCreateContext({ children }: { children: React.ReactNode; }) {
    const [addressStores, setAddressStores] = useState<interfaceBuscarCredenciadosFiltros[]>([]);
    const [states, setStates] = useState<string>('');
    const [cityes, setCityes] = useState<string>('');
    const [getZoom, setZoom] = useState<number>(10);
    const [searchData, setSearchData] = useState<string>('');
    const [openModalIndicatio, setOpenModalIndication] = useState<boolean>(false);
    const [isModalOpen, setModalOpen] = useState(false);
    const [openMap, setopenmap] = useState<boolean>(false);
    const [statesId, setStatesId] = useState<string>('');
    const [cityesId, setCityesId] = useState<string>('');
    const [neighborhood, setNeighborhood] = useState<string>('');
    const [speciality, setSpeciality] = useState<string>('');
    const [laboratory, setLaboratory] = useState<boolean | undefined>();
    const [plantation, setPlantation] = useState<boolean | undefined>();
    const [closeMenu, setCloseMenu] = useState<boolean>(true);
    const [modalDepoimentos, setModalDepoimentos] = useState<string>('');
    const [modalComunicado, setModalComunicado] = useState<boolean>(false);
    const [job, setJob] = useState<Jobs>({} as Jobs);
    const [adesoes, setAdesoes] = useState<IAdesoes[]>([]);
    const [getCenter, setCenter] = useState<IPosition[]>([{ lat: -19.922675695633668, lng: -43.937140597349114 }]);
    const [postMaisRecente, setPostMaisRecente] = useState<ViewSitePosts>();
    const [postMaisAcessados, setPostMaisAcessados] = useState<ViewSitePostsMaisAcessados[] | undefined>([]);
    const [postMaisContinueLendo, setPostContinueLendo] = useState<ViewSitePostsMaisAcessados[] | undefined>([]);
    const [specialityId, setSpecialityId] = useState<string>('');
    const [specialityNome, setSpecialityNome] = useState<string>('');



    const searchCredentialPerState = async ({ statesId, cityesId, laboratory, neighborhood, plantation , specialityId }: ISearchCredentialPerState) => {
        let params = statesId ? `EstadosId=${statesId}` : '';

        params += cityesId && cityesId !== 'Cidade' ? (params ? '&' : '') + `CidadesId=${cityesId}` : '';
        params += neighborhood && neighborhood !== 'Bairro' ? `&Bairro=${neighborhood}` : '';
        params += plantation ? (params ? '&' : '') + `CredenciadosPlantao24h=1` : '';
        params += laboratory ? (params ? '&' : '') + `CredenciadosPossuiLaboratorio=1` : '';
        params += specialityId ? (params ? '&' : '') + `EspecialidadesId=${specialityId}` : '';

        setNeighborhood(neighborhood ?? '');
        setLaboratory(laboratory ?? undefined);
        setPlantation(plantation ?? undefined);
        setSpecialityId(specialityId ?? '');

        try {
            const res = await getInitDataAccredited(params);
            setAddressStores(!!res.erro ? [] : res);

            if (res.erro) {
                setOpenModalIndication(!openModalIndicatio);
            }

            setModalOpen(false)
            const locationsAccredited = res
                .map((position: { IndividuosEnderecos: { Latitude: string, Longitude: string } }) => ({
                    lat: parseFloat(position.IndividuosEnderecos.Latitude),
                    lng: parseFloat(position.IndividuosEnderecos.Longitude),
                })).filter(({ lat, lng }: { lat: number, lng: number }) => !isNaN(lat) && !isNaN(lng))

            setCenter(locationsAccredited);

            setZoom(10);
        } catch {
        }
    };

    useEffect(() => {
        let request = true;
        if (request) {
            fetch(`${API_URL}Vendas/BuscarVendaSiteDoDia`, { headers: { 'Authorization': `${TOKEN}` } })
                .then(res => res.json())
                .then(data => {
                    setAdesoes(Object.values(data));
                })
        }
        return () => { request = false; }
    }, [])

    return (
        <CredentialContext.Provider
            value={{
                searchCredentialPerState,
                getCenter,
                getZoom,
                addressStores,
                openModalIndicatio,
                setOpenModalIndication,
                searchData,
                setSearchData,
                setCenter,
                setStates,
                setCityes,
                states,
                cityes,
                openMap,
                setopenmap,
                setModalOpen,
                isModalOpen,
                setStatesId,
                setCityesId,
                statesId,
                cityesId,
                neighborhood,
                laboratory,
                plantation,
                setNeighborhood,
                setLaboratory,
                setPlantation,
                closeMenu,
                setCloseMenu,
                modalDepoimentos,
                setModalDepoimentos,
                modalComunicado,
                setModalComunicado,
                job,
                setJob,
                adesoes,
                setAdesoes,
                postMaisRecente,
                setPostMaisRecente,
                postMaisAcessados,
                setPostMaisAcessados,
                postMaisContinueLendo,
                setPostContinueLendo,
                specialityId,
                setSpecialityId,
                specialityNome,
                setSpecialityNome
            }}
        >
            {children}
        </CredentialContext.Provider>
    );
}

export function useCredentialContext(): ICredentialContext {
    const context = useContext(CredentialContext);

    if (!context) {
        throw new Error('useCredentialContext precisa ser utilizado dentro de Providers');
    }

    return context;
}