import { defineStore } from "pinia";
import { ref } from "vue";
import { getBudgets,  getCompany, updateBudget, updateCompany, deleteBudget, createBudget, getUsers, updateUser, createUser, deleteUser, getLocations, createLocation, updateLocation, deleteLocation } from "../services/company";
import api from "../lib/axios";
import { saveProposal, updateProposal } from "../services/vehicles";
import { useI18n } from "vue-i18n";

export const useCompanyStore = defineStore('company', () => {

    const company = ref(null)
    const users = ref([]);
    const drivers = ref([]);
    const usersTotal = ref(0);
    const usersCurrentPage = ref(0);
    const budgets = ref([]);
    const budgetsTotal = ref(0);
    const budgetsCurrentPage = ref(0);
    const locations = ref([]);
    const locationsLoads = ref([]);
    const locationsTotal = ref(0);
    const locationsCurrentPage = ref(0);
    const proposals = ref([]);
    const proposalsTotal = ref(0);
    const proposalsCurrentPage = ref(0)
    const loading = ref(false);
    const { t } = useI18n();

    const getCompanyData = async() => {
        const companyId = localStorage.getItem('id');
        console.log({companyId});
        loading.value = true;
        if(!company.value) {
            loading.value = true;
            const resp = await getCompany();
            company.value = resp;
        }
        loading.value = false;
    }

    const getUsersCompany = async(limit = 1, page = 0, reload = false) => {
        const companyId = localStorage.getItem('id');
        console.log(companyId);
        if(users.value.length <= 0 || reload === true) {
            // const filter = `company=${companyId}`;
            const filter = `company=${companyId}&elements=${limit}&page=${page}`;
            const resp = await getUsers(filter);
            if(resp !== null && resp.total > 0) {
                usersTotal.value = resp.total;
                users.value = resp.data;
            } else {
                users.value = [];
            }
        }
    }

    const getDrivers = async() => {
        const companyId = localStorage.getItem('id');
        if(drivers.value.length <= 0) {
            const filter = `company=${companyId}&elements=100&job_role=driver`;
            const resp = await getUsers(filter);
            if(resp !== null && resp.total > 0) {
                drivers.value = resp.data;
            } else {
                drivers.value = [];
            }
        }
    }


    const createUserCompany = async(formData, localData) => {
        const data = await createUser(formData);
        if(data) {
            users.value.unshift({
                ...data,
                ...localData
            });
            usersTotal.value++;
            if(data.job_role === 'driver' && drivers.value.length > 0) {
                drivers.value.unshift({
                    ...data,
                    ...localData
                })
            }
            return 'success';
        } else {
            return t('errors.generic');
        }
    }

    const updateUserCompany = async(id, formData, localData) => {
        const data = await updateUser(id, formData);
        if(data) {
            const index = users.value.findIndex((user) => user._id === id);
            if(index !== -1) {
                users.value[index] = {
                    ...users.value[index],
                    ...data,
                    ...localData
                };
                if(data.job_role === 'driver' && drivers.value.length > 0) { // Actualizamos en la lista drivers
                    const indexd = drivers.value.findIndex((user) => user._id === id);
                    if(indexd !== -1) {
                        drivers.value[indexd] = {
                            ...drivers.value[index],
                            ...data,
                            ...localData
                        };
                    }
                }
            }
            return 'success';
        } else {
            return t('errors.generic');
        }
    }

    const deleteUserCompany = async(id) => {
        const data = await deleteUser(id);
        if(data) {
            users.value = users.value.filter(user => user._id !== id);
            if(data.job_role === 'driver' && drivers.value.length > 0) {
                drivers.value = drivers.value.filter(user => user._id !== id);
            }
            return 'success';
        } else {
            return t('errors.generic');
        }
    }

    const editCompany = async(formData) => {
        const data = await updateCompany(formData);
        if(data === null) {
            return t('errors.generic');
        } else {
            company.value = {
                ...company.value,
                ...formData,
            };

            return 'success';
        }
    }

    const clear = () => { //Cuando se cierra la sesion
        company.value = null;
        users.value = [];
        drivers.value = [];
        usersTotal.value = 0;
        usersCurrentPage.value = 0;
        budgets.value = [];
        budgetsTotal.value = 0;
        budgetsCurrentPage.value = 0;
        locations.value = [];
        locationsLoads.value = [];
        locationsTotal.value = 0;
        locationsCurrentPage.value = 0;
        proposals.value = [];
        proposalsTotal.value = 0;
        proposalsCurrentPage.value = 0;
        // companyid = null;
        loading.value = false;
    }

    const $reset = () => {
        company.value = null;
        // companyid = null;
        loading.value = false;
    }


    ///loads?company=64fa70c130d2650011ac4f3a&status[$ne]=Closed,posted_by_name[$regex]=ju&posted_by_name[$options]=i

    const getProposalsCompany = async(filter, reload = false) => {
        const companyId = localStorage.getItem('id');
        try {
            if(proposals.value.length <= 0 || reload) {
                const endpoint = `/v1/proposals/find?carrier=${companyId}&${filter}&$sort%5BcreatedAt%5D=-1`;
                console.log(endpoint)
                const {data} = await api.get(endpoint);
                proposals.value = data.data;
                proposalsTotal.value = data.total;
            }
        } catch (error) {
            proposals.value = [];
            proposalsTotal.value = 0;
        }
    }

    const createPropsal = async(formData) => {
        const data = await saveProposal(formData);
        if(data) {
            proposalsTotal.value++;
            return 'success';
        } else {
            return t('errors.generic');
        }
    }

    const updatePropsalLoad = async(id, formData, localData) => {
        const data = await updateProposal(id, formData);
        if(data) {
            const index = proposals.value.findIndex((prop) => prop._id === id);
            proposals.value[index] = {
                ...proposals.value[index],
                ...data,
                ...localData
            };
            return 'success';
        } else {
            return t('errors.generic');
        }
    }

    const getBudgetsCompany = async(filterQuery, reload = false) => { //here
        let filterArr = Object.values(filterQuery);

        let cleanfilterArr =  filterArr.filter(n=>n);
        var filterStr = "";
        if(cleanfilterArr.length >0){
            filterStr ="?"+cleanfilterArr.join("&");
        }

        if(budgets.value.length <= 0 || reload === true) {
            try {
                const data = await getBudgets(filterStr);
                console.log(data.total);
                if(data.total > 0) {
                    budgets.value = data.data;
                    budgetsTotal.value = data.total;
                } else {
                    budgetsTotal.value = 0;
                    budgets.value = [];
                }
            } catch (error) {
                budgets.value = [];
            }
        }
    }

    const updateBudgetCompany = async(id, formData, localData) => {
        try {
            const data = await updateBudget(id, formData);
            if(data) {
                const index = budgets.value.findIndex((budget) => budget._id === id);
                budgets.value[index] = {
                    ...budgets.value[index],
                    ...data,
                    ...localData
                };
                return 'success';
            } else {
                return 'No se pudo actualizar presupuesto, intente mas tarde';
            }
        } catch (error) {
            return t('errors.generic');
        }
    } 

    const createBudgetCompany = async(formData, localData) => {
        try {
            const data = await createBudget(formData);
            if(data) {
                budgetsTotal.value++;
                budgets.value.push({
                    ...data,
                    ...localData
                });
                return 'success';
            } else {
                return 'No se pudo agregar presupuesto, intente mas tarde';
            }
        } catch (error) {
            return t('errors.generic');
        }
    } 

    const deleteBudgetCompany = async(id) => {
        try {
            const data = await deleteBudget(id);
            if(data) {
                budgetsTotal.value--;
                budgets.value = budgets.value.filter(budget => budget._id !== id);
                return data;
            } else {
                return null;
            }
        } catch (error) {
            return null;
        }
    } 

    const getLocationsCompany = async(filterQuery, reload = false) => {
        let filterArr = Object.values(filterQuery);

        let cleanfilterArr =  filterArr.filter(n=>n);
        var filterStr = "";
        if(cleanfilterArr.length > 0){
            filterStr ="?"+cleanfilterArr.join("&");
        }
        if(locations.value.length <= 0 || reload === true) {
            const resp = await getLocations(filterStr);
            if(resp !== null && resp.total > 0) {
                locations.value = resp.data;
                locationsTotal.value = resp.total;
            } else {
                locations.value = [];
            }
        }
    }

    const getLocationsLoads = async() => {
        if(locationsLoads.value.length <= 0) {
            const filterStr = "?company="+ localStorage.getItem('id') + '&$limit=100'
            const resp = await getLocations(filterStr);
            if(resp !== null && resp.total > 0) {
                locationsLoads.value = resp.data;
            } else {
                locationsLoads.value = [];
            }
        }
    }

    const createLocationCompany = async(formData, localData) => {
        const data = await createLocation(formData);
        if(data) {
            locations.value.unshift({
                ...data,
                ...localData
            });
            locationsTotal.value++;
            locationsLoads.value.unshift({
                ...data,
                ...localData
            })
            return 'success';
        } else {
            return t('errors.generic');
        }
    }

    const updateLocationCompany = async(id, formData, localData) => {
        const data = await updateLocation(id, formData);
        if(data) {
            const index = locations.value.findIndex((loc) => loc._id === id);
            if(index !== -1) {
                locations.value[index] = {
                    ...locations.value[index],
                    ...data,
                    ...localData
                };
                if(locationsLoads.value.length > 0) {
                    const indexl = locationsLoads.value.findIndex((loc) => loc._id === id);
                    locationsLoads.value[indexl] = {
                        ...locationsLoads.value[index],
                        ...data,
                        ...localData
                    };
                }
            }
            return 'success';
        } else {
            return t('errors.generic');
        }
    }

    const deleteLocationCompany = async(id) => {
        const data = await deleteLocation(id);
        if(data) {
            locations.value = locations.value.filter(loc => loc._id !== id);
            if(locationsLoads.value.length > 0) {
                locationsLoads.value = locationsLoads.value.filter(loc => loc._id !== id);
            }

            return 'success';
        } else {
            return t('errors.generic');
        }
    }


   return {
       getCompanyData,
       getProposalsCompany,
       createPropsal,
       updatePropsalLoad,
       getBudgetsCompany,
       getUsersCompany,
       getDrivers,
       createUserCompany,
       updateUserCompany,
       deleteUserCompany,
       editCompany,
       updateBudgetCompany,
       createBudgetCompany,
       deleteBudgetCompany,
       getLocationsCompany,
       getLocationsLoads,
       createLocationCompany,
       updateLocationCompany,
       deleteLocationCompany,
       budgets,
       budgetsCurrentPage,
       budgetsTotal,
       users,
       drivers,
       usersTotal,
       usersCurrentPage,
       locations,
       locationsLoads,
       locationsTotal,
       locationsCurrentPage,
       clear,
       $reset,
       loading,
       proposals,
       proposalsCurrentPage,
       proposalsTotal,
       company,
   }
});