import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import { formsApi, FormDTO, CreateFormRequest, PageResponse } from '../../endpoints/hr/forms';
import { enqueueSnackbar } from 'notistack';

export interface FormsState {
  // Data
  forms: FormDTO[];
  currentForm: FormDTO | null;
  totalElements: number;
  totalPages: number;
  currentPage: number;
  pageSize: number;
  
  // Loading states
  loading: boolean;
  creating: boolean;
  updating: boolean;
  deleting: boolean;
  
  // Filters
  searchQuery: string;
  
  // Actions
  fetchForms: (page?: number, size?: number) => Promise<void>;
  fetchFormById: (id: string) => Promise<void>;
  searchForms: (query: string, page?: number, size?: number) => Promise<void>;
  createForm: (data: CreateFormRequest) => Promise<string | null>;
  updateForm: (id: string, data: Partial<FormDTO>) => Promise<void>;
  deleteForm: (id: string) => Promise<void>;
  
  // Filters
  setSearchQuery: (query: string) => void;
  setPage: (page: number) => void;
  setPageSize: (size: number) => void;
  clearFilters: () => void;
  
  // Utility
  resetState: () => void;
}

const initialState = {
  forms: [],
  currentForm: null,
  totalElements: 0,
  totalPages: 0,
  currentPage: 0,
  pageSize: 20,
  loading: false,
  creating: false,
  updating: false,
  deleting: false,
  searchQuery: '',
};

export const useFormsStore = create<FormsState>()(
  devtools(
    (set, get) => ({
      ...initialState,

      // Fetch all forms
      fetchForms: async (page = 0, size = 20) => {
        set({ loading: true });
        try {
          const response = await formsApi.getAllForms(page, size);
          
          const isDirectArray = Array.isArray(response);
          const forms: FormDTO[] = isDirectArray
            ? (response as FormDTO[])
            : (response as PageResponse<FormDTO>).content;
          
          set({
            forms,
            totalElements: isDirectArray
              ? forms.length
              : (response as PageResponse<FormDTO>).totalElements,
            totalPages: isDirectArray ? 1 : (response as PageResponse<FormDTO>).totalPages,
            currentPage: page,
            pageSize: size,
            loading: false,
          });
        } catch (error) {
          console.error('Error fetching forms:', error);
          enqueueSnackbar('Erreur lors du chargement des formulaires', { variant: 'error' });
          set({ loading: false });
        }
      },

      // Fetch form by ID
      fetchFormById: async (id) => {
        set({ loading: true });
        try {
          const form = await formsApi.getFormById(id);
          set({ currentForm: form, loading: false });
        } catch (error) {
          console.error('Error fetching form:', error);
          enqueueSnackbar('Erreur lors du chargement du formulaire', { variant: 'error' });
          set({ loading: false });
        }
      },

      // Search forms
      searchForms: async (query, page = 0, size = 20) => {
        set({ loading: true, searchQuery: query });
        try {
          const response = await formsApi.searchForms(query, page, size);
          set({
            forms: response.content,
            totalElements: response.totalElements,
            totalPages: response.totalPages,
            currentPage: page,
            pageSize: size,
            loading: false,
          });
        } catch (error) {
          console.error('Error searching forms:', error);
          enqueueSnackbar('Erreur lors de la recherche', { variant: 'error' });
          set({ loading: false });
        }
      },

      // Create form
      createForm: async (data) => {
        set({ creating: true });
        try {
          const result = await formsApi.createForm(data);
          enqueueSnackbar('Formulaire créé avec succès', { variant: 'success' });
          
          const { currentPage, pageSize } = get();
          await get().fetchForms(currentPage, pageSize);
          
          set({ creating: false });
          return result.id;
        } catch (error: any) {
          console.error('Error creating form:', error);
          const message = error.response?.data?.message || 'Erreur lors de la création du formulaire';
          enqueueSnackbar(message, { variant: 'error' });
          set({ creating: false });
          return null;
        }
      },

      // Update form
      updateForm: async (id, data) => {
        set({ updating: true });
        try {
          await formsApi.updateForm(id, data);
          enqueueSnackbar('Formulaire mis à jour avec succès', { variant: 'success' });
          
          const { forms } = get();
          const updatedForms = forms.map(form =>
            form.id === id ? { ...form, ...data } : form
          );
          set({ forms: updatedForms, updating: false });
          
          const { currentForm } = get();
          if (currentForm?.id === id) {
            set({ currentForm: { ...currentForm, ...data } });
          }
        } catch (error: any) {
          console.error('Error updating form:', error);
          const message = error.response?.data?.message || 'Erreur lors de la mise à jour';
          enqueueSnackbar(message, { variant: 'error' });
          set({ updating: false });
        }
      },

      // Delete form
      deleteForm: async (id) => {
        set({ deleting: true });
        try {
          await formsApi.deleteForm(id);
          enqueueSnackbar('Formulaire supprimé avec succès', { variant: 'success' });
          
          const { forms } = get();
          const filteredForms = forms.filter(form => form.id !== id);
          set({ forms: filteredForms, deleting: false });
          
          const { currentForm } = get();
          if (currentForm?.id === id) {
            set({ currentForm: null });
          }
        } catch (error: any) {
          console.error('Error deleting form:', error);
          const message = error.response?.data?.message || 'Erreur lors de la suppression';
          enqueueSnackbar(message, { variant: 'error' });
          set({ deleting: false });
        }
      },

      // Filter setters
      setSearchQuery: (query) => set({ searchQuery: query }),
      setPage: (page) => set({ currentPage: page }),
      setPageSize: (size) => set({ pageSize: size }),
      
      clearFilters: () => set({
        searchQuery: '',
        currentPage: 0,
      }),

      // Reset state
      resetState: () => set(initialState),
    }),
    {
      name: 'forms-store',
    }
  )
); 