import React from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Dimensions, StatusBar } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { useTheme } from '@/shared/styles/useTheme';
import type { StackNavigationProp } from '@react-navigation/stack';
import type { IntegrationsStackParamList } from '@/modules/integrations/navigation/IntegrationsNavigator';
import { useNavigation } from '@react-navigation/native';
import { useDispatch } from 'react-redux';
import GradientBackground from '@/shared/components/layout/GradientBackground';
import { Container, ConfirmModal } from '@/shared/components/ui';
import { logout } from '@/modules/auth/store/authSlice';
import { clearSelectedService } from '@/modules/integrations/store/integrationsSlice';

type Nav = StackNavigationProp<IntegrationsStackParamList, 'IntegrationsHome'>;

const categories = [
  { key: 'operations', title: 'Operations', icon: 'cog' },
  { key: 'finance', title: 'Accounting & Finance Integration', icon: 'currency-usd' },
  { key: 'hr', title: 'HR Systems Integration', icon: 'account-group' },
  { key: 'crm', title: 'CRM & Sales Integration', icon: 'chart-line' },
  { key: 'collab', title: 'Communication & Collaboration', icon: 'message' },
  { key: 'storage', title: 'File Storage & Document Management', icon: 'folder' },
];

const NUM_COLUMNS = 2;
const GUTTER = 12;
const screenWidth = Dimensions.get('window').width;
const CARD_WIDTH = (screenWidth - GUTTER * (NUM_COLUMNS + 1)) / NUM_COLUMNS;

interface Props {
  navigation: Nav;
}

const IntegrationsHomeScreen: React.FC<Props> = () => {
  const { colors, shadows, fonts } = useTheme();
  const navigation = useNavigation();
  const dispatch = useDispatch();

  const [showLogout, setShowLogout] = React.useState(false);
  const handleLogout = () => setShowLogout(true);
  const handleConfirmLogout = () => {
    setShowLogout(false);
    dispatch(clearSelectedService());
    dispatch(logout());
  };
  const handleCancelLogout = () => setShowLogout(false);

  return (
    <GradientBackground colors={['#FFE9CC', '#F6E6FF']} style={{flex:1}}>
    
    <View style={[styles.container]}> 
      {/* Header with title and logout button */}
      <View style={styles.header}>
        <Text style={[styles.title, { color: colors.text, fontFamily: fonts.bold }]}>Choose a Service</Text>
        <TouchableOpacity
          style={[styles.logoutButton, { backgroundColor: colors.surface, borderColor: colors.border }]}
          onPress={handleLogout}
          activeOpacity={0.8}
        >
          <Icon name="logout" size={20} color={colors.text} />
        </TouchableOpacity>
      </View>
      <FlatList
        data={categories}
        keyExtractor={item => item.key}
        numColumns={NUM_COLUMNS}
        contentContainerStyle={{ padding: GUTTER }}
        columnWrapperStyle={{ justifyContent: 'space-between' }}
        renderItem={({ item }) => (
          <TouchableOpacity
            activeOpacity={0.8}
            // @ts-ignore
            onPress={() => navigation.navigate('IntegrationCategory', { categoryKey: item.key, title: item.title })}
            style={[
              styles.card,
              { backgroundColor: colors.surface, borderColor: colors.border, width: CARD_WIDTH, ...shadows.light },
            ]}
          >
            <View style={[styles.iconCircle, { backgroundColor: '#F1F5F9' }]}>
              <Icon name={item.icon} size={24} color={colors.primary} />
            </View>
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]} numberOfLines={2}>
              {item.title}
            </Text>
          </TouchableOpacity>
        )}
      />
    </View>

    {/* Logout Confirmation Modal */}
    <ConfirmModal
      visible={showLogout}
      title="Logout"
      message="Are you sure you want to logout?"
      confirmText="Logout"
      cancelText="Cancel"
      onConfirm={handleConfirmLogout}
      onCancel={handleCancelLogout}
    />
    </GradientBackground>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: 12,
    marginHorizontal: GUTTER,
    marginBottom: 4,
  },
  title: {
    fontSize: 20,
    flex: 1,
  },
  logoutButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    borderWidth: 1,
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: 12,
  },
  card: {
    borderRadius: 12,
    borderWidth: 1,
    padding: 12,
    marginBottom: GUTTER,
    alignItems: 'center',
  },
  iconCircle: {
    width: 40,
    height: 40,
    borderRadius: 8,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 8,
  },
  cardTitle: {
    fontSize: 14,
    textAlign: 'center',
  },
});

export default IntegrationsHomeScreen;


