import {
  createContext,
  type ReactNode,
  useContext,
  useMemo,
  useState,
} from 'react';

import { useAuth } from 'src/contexts/JWTContext';
import { type ReportFilterFields } from 'src/types/timeTracking';
import { getTodayInTimezone } from 'src/utils/timeTracking';

type CollaboratorsState = {
  fromDate: Date;
  toDate: Date;
  search: string;
  reportFilters: ReportFilterFields | null;
  totalRecords: number;
};

// Context
const CollaboratorsContext = createContext<{
  state: CollaboratorsState;
  setState: React.Dispatch<React.SetStateAction<CollaboratorsState>>;
} | null>(null);

// Provider
type CollaboratorsProviderProps = {
  children: ReactNode;
};

export const CollaboratorsProvider = ({
  children,
}: CollaboratorsProviderProps) => {
  const { instance } = useAuth();
  const [state, setState] = useState<CollaboratorsState>({
    fromDate: getTodayInTimezone(instance?.timezone!),
    toDate: getTodayInTimezone(instance?.timezone!),
    search: '',
    reportFilters: null,
    totalRecords: 0,
  });

  // Memoize the context value to prevent unnecessary re-renders
  const contextValue = useMemo(() => ({ state, setState }), [state]);

  return (
    <CollaboratorsContext.Provider value={contextValue}>
      {children}
    </CollaboratorsContext.Provider>
  );
};

// Context hook
export const useTimeTrackingCollaborators = () => {
  const context = useContext(CollaboratorsContext);
  if (!context) {
    throw new Error(
      'useTimeTrackingCollaborators must be used within a CollaboratorsProvider',
    );
  }
  return context;
};

export const useTimeTrackingCollaboratorsActions = () => {
  const { state, setState } = useTimeTrackingCollaborators();

  const setFromDate = (date: Date) => {
    setState(prev => ({ ...prev, fromDate: date }));
  };

  const setToDate = (date: Date) => {
    setState(prev => ({ ...prev, toDate: date }));
  };

  const setSearch = (search: string) => {
    setState(prev => ({ ...prev, search }));
  };

  const setReportFilters = (filters: ReportFilterFields) => {
    setState(prev => ({ ...prev, reportFilters: filters }));
  };

  const setTotalRecords = (total: number) => {
    setState(prev => ({ ...prev, totalRecords: total }));
  };

  return {
    ...state,
    // Actions
    setFromDate,
    setToDate,
    setSearch,
    setReportFilters,
    setTotalRecords,
  };
};
