import { create } from 'zustand';
import { endpoints } from '../../endpoints/admin-service';
import axiosInstance from '@/utils/axios';
import { Contract, ContractList, ContractPageFilterParams, ContractRequest, ContractStatus } from '@/shared/types/contract';


type ContractStore = {
  loading: boolean;
  error: string | null;
  contracts: ContractList[];
  totalElements: number;
  fetchContractsPage: (params?: ContractPageFilterParams) => Promise<void>;
  contractById: Contract | null;
  getContractById: (id: string) => Promise<Contract | null>;
  createContract: (contract: ContractRequest) => Promise<void>;
  toogleActivation: (id: string, isActive: boolean) => Promise<void>;
  updateContract: (id: string, contract: ContractRequest) => Promise<void>;
  startExportFiltredContracts: (params?: ContractPageFilterParams) => Promise<void>;
  updateContractStatus: (id: string, newStatus: ContractStatus) => Promise<void>;
};

export const useContractStore = create<ContractStore>((set) => ({
  loading: false,
  error: null,
  contracts: [],
  totalElements: 0,
  fetchContractsPage: async (params) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(endpoints.Admin.Contract.getContractsPage, {
        params,
      });

      const { content, totalElements } = response.data;
      set({
        contracts: content,
        totalElements,
        loading: false,
      });
    } catch (error: any) {
      set({
        error: error.message || 'Failed to fetch contracts',
        loading: false,
      });
    }
  },
  contractById: null,
  getContractById: async (id) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(endpoints.Admin.Contract.getContractById(id));
      set({ loading: false, contractById: response.data as Contract });
      return response.data as Contract;
    } catch (error: any) {
      set({
        error: error.message || 'Failed to fetch contract by ID',
        loading: false,
      });
      return null;
    }
  },
  createContract: async (contract) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post(endpoints.Admin.Contract.createContract, contract);
      set((state) => ({
        contracts: [...state.contracts, response.data],
        loading: false,
      }));
    } catch (error: any) {
      set({
        error: error.message || 'Failed to create contract',
        loading: false,
      });
    }
  },
  toogleActivation: async (id, isActive) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post<boolean>(endpoints.Admin.Contract.toogleActivation(id, isActive));
      set((state) => ({
        contracts: state.contracts.map((c) => (c.id === id ? { ...c, active: response.data } : c)),
        loading: false,
      }));
    } catch (error: any) {
      set({
        error: error.message || 'Failed to toggle activation',
        loading: false,
      });
    }
  },
  updateContract: async (id, contract) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post<ContractStatus>(endpoints.Admin.Contract.updateContract(id), contract);
      set((state) => ({
        contracts: state.contracts.map((c) => (c.id === id ? { ...c, status: response.data } : c)),
        loading: false,
      }));
    } catch (error: any) {
      set({
        error: error.message || 'Failed to update contract',
        loading: false,
      });
    }
  },
  startExportFiltredContracts: async (params) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post(endpoints.Admin.Contract.startExportFiltredContracts, { params });
      return response.data;
    } catch (error: any) {
      set({
        error: error.message || 'Failed to start export contracts',
        loading: false,
      });
    }
  },
  updateContractStatus: async (id, newStatus) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post<ContractStatus>(
        endpoints.Admin.Contract.updateContractStatus(id), null, { params: { newStatus } }
      );
      set((state) => ({
        contracts: state.contracts.map((c) => (c.id === id ? { ...c, status: response.data } : c)),
        loading: false,
      }));
    } catch (error: any) {
      set({
        error: error.message || 'Failed to update contract status',
        loading: false,
      });
    }
  },
}));