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 } from '@components';
import { useAppDispatch, useAppSelector, RootState } from '@store';
import { getDashboardLeadCount } 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>('year');

  const user_data = useAppSelector((state: RootState) => state.auth.user_data);
  const { leadCountData, loading, error } = 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]);
  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}
      />
    </ScrollView>
  );
};


