import React, { useState, useEffect, useMemo } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  RefreshControl,
  FlatList,
  Alert,
} from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import type { AppDispatch } from '@/store/store';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { Container, LoadingSpinner, ErrorState } from '@/shared/components/ui';
import { useTheme } from '@/shared/styles/useTheme';
import { showError, showSuccess, showInfo } from '@/shared/utils/Toast';
import type { 
  ZohoProject, 
  ZohoTask, 
  ZohoIssue, 
  ZohoPhase 
} from '../types/ZohoProjectsTypes';
import { 
  ProjectCard, 
  TaskCard, 
  IssueCard, 
  PhaseCard 
} from '../components/ZohoProjectsDataCards';
import { 
  selectZohoProjects,
  selectZohoTasks,
  selectZohoIssues,
  selectZohoPhases,
  selectZohoProjectsLoading,
  selectZohoProjectsErrors
} from '../store/selectors';
import { fetchAllZohoProjectsData } from '../store/zohoProjectsSlice';
import type { RootState } from '@/store/store';

const ZohoProjectsDataScreen: React.FC = () => {
  const { colors, fonts, spacing, shadows } = useTheme();
  const dispatch = useDispatch<AppDispatch>();
  const [selectedTab, setSelectedTab] = useState<'projects' | 'tasks' | 'issues' | 'phases'>('projects');
  const [refreshing, setRefreshing] = useState(false);

  // Redux selectors
  const projects = useSelector(selectZohoProjects);
  const tasks = useSelector(selectZohoTasks);
  const issues = useSelector(selectZohoIssues);
  const phases = useSelector(selectZohoPhases);
  const loading = useSelector(selectZohoProjectsLoading);
  const errors = useSelector(selectZohoProjectsErrors);

  // Create Zoho Projects data object from Redux state
  const zohoProjectsData = useMemo(() => ({
    projects: projects || [],
    tasks: tasks || [],
    issues: issues || [],
    phases: phases || [],
  }), [projects, tasks, issues, phases]);

  // Fetch Zoho Projects data using Redux
  const fetchZohoProjectsData = async (showRefresh = false) => {
    try {
      if (showRefresh) {
        setRefreshing(true);
      }

      // Dispatch Redux action to fetch all Zoho Projects data
      await dispatch(fetchAllZohoProjectsData({ refresh: showRefresh })).unwrap();
      
      if (showRefresh) {
        showSuccess('Zoho Projects data refreshed successfully');
      }
    } catch (err) {
      const errorMessage = 'Failed to fetch Zoho Projects data';
      showError(errorMessage);
    } finally {
      setRefreshing(false);
    }
  };

  useEffect(() => {
    fetchZohoProjectsData();
  }, []);

  const handleRefresh = () => {
    fetchZohoProjectsData(true);
  };

  const handleRetry = () => {
    fetchZohoProjectsData();
  };

  const handleCardPress = (item: any, type: string) => {
    showInfo(`Viewing ${type}: ${item.name || item.prefix + item.name || 'Unknown'}`);
  };

  // Get current loading state and error
  const isLoading = loading.projects || loading.tasks || loading.issues || loading.phases;
  const hasError = errors.projects || errors.tasks || errors.issues || errors.phases;

  // Tab configuration
  const tabs = [
    { 
      key: 'projects', 
      label: 'Projects', 
      icon: 'folder-multiple', 
      count: zohoProjectsData.projects.length 
    },
    { 
      key: 'tasks', 
      label: 'Tasks', 
      icon: 'check-circle', 
      count: zohoProjectsData.tasks.length 
    },
    { 
      key: 'issues', 
      label: 'Issues', 
      icon: 'alert-circle', 
      count: zohoProjectsData.issues.length 
    },
    { 
      key: 'phases', 
      label: 'Phases', 
      icon: 'timeline', 
      count: zohoProjectsData.phases.length 
    },
  ] as const;

  if (isLoading && !zohoProjectsData.projects.length) {
    return <LoadingSpinner />;
  }

  if (hasError && !zohoProjectsData.projects.length) {
    return <ErrorState onRetry={handleRetry} />;
  }

  const renderTabContent = () => {
    const commonFlatListProps = {
      numColumns: 1,
      showsVerticalScrollIndicator: false,
      contentContainerStyle: styles.listContainer,
      refreshControl: (
        <RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />
      ),
    };

    switch (selectedTab) {
      case 'projects':
        return (
          <FlatList
            data={zohoProjectsData.projects}
            renderItem={({ item }) => (
              <ProjectCard
                project={item}
                onPress={() => handleCardPress(item, 'Project')}
              />
            )}
            keyExtractor={(item) => item.id}
            {...commonFlatListProps}
          />
        );
      case 'tasks':
        return (
          <FlatList
            data={zohoProjectsData.tasks}
            renderItem={({ item }) => (
              <TaskCard
                task={item}
                onPress={() => handleCardPress(item, 'Task')}
              />
            )}
            keyExtractor={(item) => item.id}
            {...commonFlatListProps}
          />
        );
      case 'issues':
        return (
          <FlatList
            data={zohoProjectsData.issues}
            renderItem={({ item }) => (
              <IssueCard
                issue={item}
                onPress={() => handleCardPress(item, 'Issue')}
              />
            )}
            keyExtractor={(item) => item.id}
            {...commonFlatListProps}
          />
        );
      case 'phases':
        return (
          <FlatList
            data={zohoProjectsData.phases}
            renderItem={({ item }) => (
              <PhaseCard
                phase={item}
                onPress={() => handleCardPress(item, 'Phase')}
              />
            )}
            keyExtractor={(item) => item.id}
            {...commonFlatListProps}
          />
        );
      default:
        return null;
    }
  };

  return (
      <View style={[styles.container, { backgroundColor: colors.background }]}>
        {/* Header */}
        <View style={styles.header}>
          <Text style={[styles.title, { color: colors.text, fontFamily: fonts.bold }]}>
            Zoho Projects Data
          </Text>
          <TouchableOpacity onPress={handleRefresh} disabled={refreshing}>
            <Icon name="refresh" size={24} color={colors.primary} />
          </TouchableOpacity>
        </View>

        {/* Fixed Tabs */}
        <View style={styles.tabsContainer}>
          <ScrollView horizontal showsHorizontalScrollIndicator={false}>
            <View style={styles.tabs}>
              {tabs.map((tab) => (
                <TouchableOpacity
                  key={tab.key}
                  style={[
                    styles.tab,
                    { backgroundColor: colors.surface, ...shadows.light },
                    selectedTab === tab.key && { backgroundColor: colors.primary },
                  ]}
                  onPress={() => setSelectedTab(tab.key)}
                  activeOpacity={0.8}
                >
                  <Icon
                    name={tab.icon}
                    size={20}
                    color={selectedTab === tab.key ? colors.surface : colors.textLight}
                  />
                  <Text
                    style={[
                      styles.tabText,
                      {
                        color: selectedTab === tab.key ? colors.surface : colors.textLight,
                        fontFamily: fonts.medium,
                      },
                    ]}
                  >
                    {tab.label}
                  </Text>
                  <View
                    style={[
                      styles.countBadge,
                      { 
                        backgroundColor: selectedTab === tab.key ? colors.surface : colors.primary 
                      },
                    ]}
                  >
                    <Text
                      style={[
                        styles.countText,
                        {
                          color: selectedTab === tab.key ? colors.primary : colors.surface,
                          fontFamily: fonts.bold,
                        },
                      ]}
                    >
                      {tab.count}
                    </Text>
                  </View>
                </TouchableOpacity>
              ))}
            </View>
          </ScrollView>
        </View>

        {/* Content */}
        <View style={styles.content}>
          {renderTabContent()}
        </View>
      </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  title: {
    fontSize: 24,
  },
  tabsContainer: {
    backgroundColor: '#FFFFFF',
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#E5E7EB',
  },
  tabs: {
    flexDirection: 'row',
    paddingHorizontal: 16,
  },
  tab: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 10,
    marginRight: 8,
    borderRadius: 20,
  },
  tabText: {
    marginLeft: 6,
    fontSize: 14,
  },
  countBadge: {
    marginLeft: 6,
    paddingHorizontal: 8,
    paddingVertical: 2,
    borderRadius: 10,
    minWidth: 20,
    alignItems: 'center',
  },
  countText: {
    fontSize: 12,
  },
  content: {
    flex: 1,
  },
  listContainer: {
    paddingHorizontal: 16,
    paddingBottom: 20,
  },
});

export default ZohoProjectsDataScreen;
