import React, { useEffect, useState } from 'react';
import { ScrollView, View, Text, InteractionManager } from 'react-native';
import { getStyles } from './dashboard.styles';
import { useTheme } from '../../theme';
import { LeadDistribution, ProjectActivityFeed } from '@components';
import { useAppDispatch, useAppSelector, RootState } from '@store';
import { getDashboardLeadCount, getDashboardProjectActivity } from './thunk';
import { NotificationService } from '@services';

export const DashboardScreen = () => {
  const dispatch = useAppDispatch();
  const { theme: colors } = useTheme();
  const styles = getStyles(colors);

  const [selectedAction, setSelectedAction] = useState<string>('all');

  const user_data = useAppSelector((state: RootState) => state.auth.user_data);
  const { leadCountData, loading, error, projectActivityData, activityLoading, activityError } = useAppSelector(
    (state: RootState) => state.dashboard,
  );

  useEffect(() => {
    const task = InteractionManager.runAfterInteractions(() => {
      NotificationService.requestPermission();
    });
    return () => task.cancel();
  }, []);

  useEffect(() => {
    if (user_data?.staffid) {
      dispatch(
        getDashboardLeadCount({
          action: selectedAction,
          staffid: user_data.staffid,
        }),
      );
    }
  }, [dispatch, selectedAction, user_data]);

  useEffect(() => {
    if (user_data?.staffid) {
      dispatch(
        getDashboardProjectActivity({
          staff_id: user_data.staffid,
        }),
      );
    }
  }, [dispatch, user_data]);
  
  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.content}>
      {error && (
        <View style={styles.errorContainer}>
          <Text style={styles.errorText}>{error}</Text>
        </View>
      )}

      {/* Lead Distribution Chart Card */}
      <LeadDistribution
        data={leadCountData}
        loading={loading}
        activeAction={selectedAction}
        onActionChange={setSelectedAction}
      />

      {activityError && (
        <View style={styles.errorContainer}>
          <Text style={styles.errorText}>{activityError}</Text>
        </View>
      )}

      {/* Project Activity Feed */}
      <ProjectActivityFeed
        data={projectActivityData}
        loading={activityLoading}
      />
    </ScrollView>
  );
};


