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";

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

    const company = ref(null)
    const users = ref([]);
    const drivers = ref([]);
    const usersTotal = ref(0);
    const usersCurrentPage = ref(1);
    const budgets = ref([]);
    const locations = ref([]);
    const locationsLoads = ref([]);
    const locationsTotal = ref(0);
    const locationsCurrentPage = ref(1);
    const proposals = ref([])
    const loading = ref(false);

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

    const getUsersCompany = async(limit = 10, skip = 0, reload = false) => {
        const companyId = localStorage.getItem('id');
        if(users.value.length <= 0 || reload === true) {
            const filter = `company=${companyId}&&$sort%5BcreatedAt%5D=-1&$limit=${limit}&$skip=${skip}`
            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}&$sort%5BcreatedAt%5D=-1&$limit=100&$skip=0&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 'Algo salio mal, intente más tarde';
        }
    }

    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 'Algo salio mal, intente más tarde';
        }
    }

    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 'Algo salio mal, intente más tarde';
        }
    }

    const editCompany = async(formData) => {
        const data = await updateCompany(company.value._id, formData);
        if(data === null) {
            return 'Algo salio mal, intente más tarde';
        } else {
            company.value = {
                ...company.value,
                ...formData,
            };

            return 'success';
        }
    }

    const clear = () => { //Cuando se cierra la sesion
        company.value = null;
        users.value = [];
        usersTotal.value = 0;
        usersCurrentPage.value = 1;
        drivers.value = [];
        budgets.value = [];
        proposals.value = [];
        locations.value = [];
        locationsLoads.value = [];
        locationsTotal.value = 0;
        locationsCurrentPage.value = 1;
        // 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() => {
        const companyId = localStorage.getItem('id');
        try {
            const endpoint = `/proposals?carrier=${companyId}`;
            const {data} = await api.get(endpoint);
            proposals.value = data.data;
        } catch (error) {
            proposals.value = [];
        }
    }

    const createPropsal = async(formData) => {
        const data = await saveProposal(formData);
        if(data) {
            return 'success';
        } else {
            return 'Algo salio mal, intente más tarde';
        }
    }

    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 'Algo salio mal, intente más tarde';
        }
    }

    const getBudgetsCompany = 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(budgets.value.length <= 0 || reload === true) {
            try {
                const data = await getBudgets(filterStr);
                if(data.total > 0) {
                    budgets.value = data.data;
                } else {
                    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 'Algo salio mal, intente más tarde';
        }
    } 

    const createBudgetCompany = async(formData, localData) => {
        try {
            const data = await createBudget(formData);
            if(data) {
                budgets.value.push({
                    ...data,
                    ...localData
                });
                return 'success';
            } else {
                return 'No se pudo agregar presupuesto, intente mas tarde';
            }
        } catch (error) {
            return 'Algo salio mal, intente más tarde';
        }
    } 

    const deleteBudgetCompany = async(id) => {
        try {
            const data = await deleteBudget(id);
            if(data) {
                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 'Algo salio mal, intente más tarde';
        }
    }

    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 'Algo salio mal, intente más tarde';
        }
    }

    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 'Algo salio mal, intente más tarde';
        }
    }


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