import { createFeature, createReducer, on } from '@ngrx/store';
import { DashboardStats } from '../../models/dashboard.model';
import { Company } from '../../models/auth.model';
import { DashboardActions } from './dashboard.actions';

export interface DashboardState {
  stats: DashboardStats | null;
  company: Company | null;
  loading: boolean;
  saving: boolean;
  error: string | null;
}

const initialState: DashboardState = {
  stats: null,
  company: null,
  loading: false,
  saving: false,
  error: null,
};

export const dashboardFeature = createFeature({
  name: 'dashboard',
  reducer: createReducer(
    initialState,
    // Load Dashboard
    on(DashboardActions.loadDashboard, (state) => ({
      ...state,
      loading: true,
      error: null,
    })),
    on(DashboardActions.loadDashboardSuccess, (state, { stats, company }) => ({
      ...state,
      stats,
      company,
      loading: false,
    })),
    on(DashboardActions.loadDashboardFailure, (state, { error }) => ({
      ...state,
      loading: false,
      error,
    })),
    // Load Company
    on(DashboardActions.loadCompany, (state) => ({
      ...state,
      loading: true,
      error: null,
    })),
    on(DashboardActions.loadCompanySuccess, (state, { company }) => ({
      ...state,
      company,
      loading: false,
    })),
    on(DashboardActions.loadCompanyFailure, (state, { error }) => ({
      ...state,
      loading: false,
      error,
    })),
    // Update Company
    on(DashboardActions.updateCompany, (state) => ({
      ...state,
      saving: true,
      error: null,
    })),
    on(DashboardActions.updateCompanySuccess, (state, { company }) => ({
      ...state,
      company,
      saving: false,
    })),
    on(DashboardActions.updateCompanyFailure, (state, { error }) => ({
      ...state,
      saving: false,
      error,
    })),
    // Clear Error
    on(DashboardActions.clearDashboardError, (state) => ({
      ...state,
      error: null,
    }))
  ),
});

export const {
  selectStats: selectDashboardStats,
  selectCompany: selectDashboardCompany,
  selectLoading: selectDashboardLoading,
  selectSaving: selectDashboardSaving,
  selectError: selectDashboardError,
} = dashboardFeature;
