import React from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { useTheme } from '@/shared/styles/useTheme';
import type { RouteProp } from '@react-navigation/native';
import type { IntegrationsStackParamList } from '@/modules/integrations/navigation/IntegrationsNavigator';
import { useDispatch } from 'react-redux';
import { setSelectedService } from '@/modules/integrations/store/integrationsSlice';
import type { AppDispatch } from '@/store/store';
import ZohoAuth from './ZohoAuth';
import { Modal } from 'react-native';

type Route = RouteProp<IntegrationsStackParamList, 'IntegrationCategory'>;

const servicesMap: Record<string, { key: string; title: string; icon: string }[]> = {
  operations: [
    { key: 'zohoProjects', title: 'Zoho Projects', icon: 'briefcase-check' },
  ],
  finance: [
    { key: 'quickbooks', title: 'QuickBooks', icon: 'finance' },
    { key: 'zohoBooks', title: 'Zoho Books', icon: 'book-open-variant' },
    { key: 'tally', title: 'Tally', icon: 'calculator-variant' },
    { key: 'xero', title: 'Xero', icon: 'bank' },
    { key: 'sapb1', title: 'SAP Business One', icon: 'factory' },
  ],
  hr: [
    { key: 'zohoPeople', title: 'Zoho People', icon: 'account' },
    { key: 'bamboohr', title: 'BambooHR', icon: 'sprout' },
    { key: 'workday', title: 'Workday', icon: 'briefcase' },
    { key: 'keka', title: 'Keka', icon: 'account-cash' },
  ],
  crm: [
    { key: 'zohoCRM', title: 'Zoho CRM', icon: 'account-box-multiple' },
    { key: 'hubspot', title: 'HubSpot', icon: 'chart-timeline-variant' },
    { key: 'salesforce', title: 'Salesforce', icon: 'cloud' },
    { key: 'pipedrive', title: 'Pipedrive', icon: 'pipe' },
  ],
  collab: [
    { key: 'slack', title: 'Slack', icon: 'slack' },
    { key: 'teams', title: 'Microsoft Teams', icon: 'microsoft-teams' },
    { key: 'zoom', title: 'Zoom', icon: 'video' },
    { key: 'gworkspace', title: 'Google Workspace', icon: 'google' },
  ],
  storage: [
    { key: 'gdrive', title: 'Google Drive', icon: 'google-drive' },
    { key: 'dropbox', title: 'Dropbox Business', icon: 'dropbox' },
    { key: 'onedrive', title: 'OneDrive', icon: 'microsoft-onedrive' },
    { key: 'sharepoint', title: 'SharePoint', icon: 'microsoft-sharepoint' },
    { key: 'box', title: 'Box', icon: 'cube' },
  ],
};

interface Props {
  route: Route;
}

const IntegrationCategoryScreen: React.FC<Props> = ({ route }) => {
  const { colors, fonts } = useTheme();
  const dispatch = useDispatch<AppDispatch>();
  const [showZohoAuth, setShowZohoAuth] = React.useState(false);
  const [pendingService, setPendingService] = React.useState<string | null>(null);
  const services = servicesMap[route.params.categoryKey] ?? [];

  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}> 
      <FlatList
        data={services}
        keyExtractor={item => item.key}
        contentContainerStyle={{ padding: 16 }}
        ItemSeparatorComponent={() => <View style={[styles.sep, { backgroundColor: colors.border }]} />}
        renderItem={({ item }) => (
          <TouchableOpacity
            style={styles.row}
            activeOpacity={0.8}
            onPress={() => {
              // Here we decide whether to require Zoho authentication first
              const requiresZohoAuth = item.key === 'zohoProjects' || item.key === 'zohoPeople' || item.key === 'zohoBooks' || item.key === 'zohoCRM';
              console.log('key pressed',item.key)
              if (requiresZohoAuth) {
                setPendingService(item.key);
                setShowZohoAuth(true);
              } else {
                dispatch(setSelectedService(item.key));
              }
            }}
          >
            <View style={[styles.iconCircle, { backgroundColor: '#F1F5F9' }]}>
              <Icon name={item.icon} size={20} color={colors.primary} />
            </View>
            <Text style={[styles.title, { color: colors.text, fontFamily: fonts.medium }]}>{item.title}</Text>
          </TouchableOpacity>
        )}
      />

      {/* Zoho Auth Modal */}
      <Modal
        visible={showZohoAuth}
        animationType="slide"
        presentationStyle="fullScreen"
        onRequestClose={() => setShowZohoAuth(false)}
      >
        <ZohoAuth
          serviceKey={pendingService as any}
          onAuthSuccess={(authData) => {
            console.log('auth data i got',authData)
            setShowZohoAuth(false);
            if (pendingService) {
              dispatch(setSelectedService(pendingService));
              setPendingService(null);
            }
          }}
          onAuthError={() => {
            setShowZohoAuth(false);
            setPendingService(null);
          }}
          onClose={() => {
            setShowZohoAuth(false);
            setPendingService(null);
          }}
        />
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1 },
  sep: { height: 1, opacity: 0.6 },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 12,
  },
  iconCircle: {
    width: 36,
    height: 36,
    borderRadius: 8,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: 12,
  },
  title: { fontSize: 14 },
});

export default IntegrationCategoryScreen;


