import React from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Alert } 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 SalesforceAuth from './SalesforceAuth';
import { Modal } from 'react-native';
import httpClient from '@/services/http';
import { useNavigation } from '@react-navigation/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 navigation = useNavigation();
  const [showZohoAuth, setShowZohoAuth] = React.useState(false);
  const [showSalesforceAuth, setShowSalesforceAuth] = React.useState(false);
  const [pendingService, setPendingService] = React.useState<string | null>(null);
  const [isCheckingToken, setIsCheckingToken] = React.useState(false);
  const [authenticatedServices, setAuthenticatedServices] = React.useState<Set<string>>(new Set());
  const services = servicesMap[route.params.categoryKey] ?? [];


  // Check for existing Zoho token
  const checkZohoToken = async (serviceKey: string, forceReauth: boolean = false) => {
    try {
      setIsCheckingToken(true);
      
      if (forceReauth) {
        // Force re-authentication by showing auth modal
        setPendingService(serviceKey);
        setShowZohoAuth(true);
        return;
      }
      
      const response = await httpClient.get('/api/v1/users/decrypt-token?service_name=zoho');
      const responseData = response.data as any;
      
      if (responseData.status === 'success' && responseData.data?.accessToken) {
        // Token exists and is valid, mark as authenticated and navigate directly
        console.log('Zoho token found, navigating directly to:', serviceKey);
        setAuthenticatedServices(prev => new Set([...prev, serviceKey]));
        dispatch(setSelectedService(serviceKey));
      } else {
        // No valid token, show auth modal
        setPendingService(serviceKey);
        setShowZohoAuth(true);
      }
    } catch (error) {
      console.log('No valid Zoho token found, showing auth modal');
      // Token doesn't exist or is invalid, show auth modal
      setPendingService(serviceKey);
      setShowZohoAuth(true);
    } finally {
      setIsCheckingToken(false);
    }
  };

  // Check for existing Salesforce token
  const checkSalesforceToken = async (serviceKey: string, forceReauth: boolean = false) => {
    try {
      setIsCheckingToken(true);
      
      if (forceReauth) {
        // Force re-authentication by showing auth modal
        setPendingService(serviceKey);
        setShowSalesforceAuth(true);
        return;
      }
      
      const response = await httpClient.get('/api/v1/users/decrypt-token?service_name=salesforce');
      const responseData = response.data as any;
      
      if (responseData.status === 'success' && responseData.data?.accessToken) {
        // Token exists and is valid, mark as authenticated
        // CrmNavigator will automatically show SalesforceDashboard based on selectedService
        console.log('Salesforce token found, setting selected service');
        setAuthenticatedServices(prev => new Set([...prev, serviceKey]));
        dispatch(setSelectedService(serviceKey));
      } else {
        // No valid token, show auth modal
        setPendingService(serviceKey);
        setShowSalesforceAuth(true);
      }
    } catch (error) {
      console.log('No valid Salesforce token found, showing auth modal');
      // Token doesn't exist or is invalid, show auth modal
      setPendingService(serviceKey);
      setShowSalesforceAuth(true);
    } finally {
      setIsCheckingToken(false);
    }
  };

  // Handle re-authentication
  const handleReAuthenticate = (serviceKey: string) => {
    const isSalesforce = serviceKey === 'salesforce';
    const serviceTitle = isSalesforce ? 'Salesforce' : 'Zoho';
    
    Alert.alert(
      'Re-authenticate',
      `This will allow you to change your ${serviceTitle} organization or re-authorize access. Continue?`,
      [
        {
          text: 'Cancel',
          style: 'cancel',
        },
        {
          text: 'Re-authenticate',
          onPress: () => {
            if (isSalesforce) {
              checkSalesforceToken(serviceKey, true);
            } else {
              checkZohoToken(serviceKey, true);
            }
          },
        },
      ]
    );
  };

  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 }) => {
          const requiresZohoAuth = item.key === 'zohoProjects' || item.key === 'zohoPeople' || item.key === 'zohoBooks' || item.key === 'zohoCRM';
          const requiresSalesforceAuth = item.key === 'salesforce';
          const requiresAuth = requiresZohoAuth || requiresSalesforceAuth;
          
          return (
            <View style={styles.serviceItem}>
              <View style={[styles.row, isCheckingToken && styles.disabledRow]}>
                <TouchableOpacity
                  style={styles.mainServiceButton}
                  activeOpacity={0.8}
                  disabled={isCheckingToken}
                  onPress={() => {
                    console.log('key pressed', item.key);
                    
                    if (requiresZohoAuth) {
                      checkZohoToken(item.key);
                    } else if (requiresSalesforceAuth) {
                      checkSalesforceToken(item.key);
                    } else {
                      // For other services, navigate to Coming Soon screen
                      navigation.navigate('ComingSoon' as never);
                    }
                  }}
                >
                  <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>
                  {isCheckingToken && (
                    <View style={styles.loadingContainer}>
                      <Text style={[styles.loadingText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                        Checking...
                      </Text>
                    </View>
                  )}
                </TouchableOpacity>
                
                {/* Re-authentication button for services that require auth */}
                {requiresAuth && (
                  <TouchableOpacity
                    style={[styles.reauthButton, { backgroundColor: colors.background, borderColor: colors.border }]}
                    onPress={() => handleReAuthenticate(item.key)}
                    activeOpacity={0.7}
                  >
                    <Icon name="refresh" size={14} color={colors.textLight} />
                    <Text style={[styles.reauthText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                      Re-auth
                    </Text>
                  </TouchableOpacity>
                )}
              </View>
            </View>
          );
        }}
      />

      {/* Zoho Auth Modal */}
      <Modal
        visible={showZohoAuth}
        animationType="slide"
        presentationStyle="fullScreen"
        onRequestClose={() => setShowZohoAuth(false)}
      >
        <ZohoAuth
          serviceKey={pendingService as any}
          onAuthSuccess={(authData) => {
            console.log('Zoho auth data received:', authData);
            setShowZohoAuth(false);
            if (pendingService) {
              // Mark service as authenticated
              setAuthenticatedServices(prev => new Set([...prev, pendingService]));
              dispatch(setSelectedService(pendingService));
              setPendingService(null);
            }
          }}
          onAuthError={() => {
            setShowZohoAuth(false);
            setPendingService(null);
          }}
          onClose={() => {
            setShowZohoAuth(false);
            setPendingService(null);
          }}
        />
      </Modal>

      {/* Salesforce Auth Modal */}
      <Modal
        visible={showSalesforceAuth}
        animationType="slide"
        presentationStyle="fullScreen"
        onRequestClose={() => setShowSalesforceAuth(false)}
      >
        <SalesforceAuth
          onAuthSuccess={(authData) => {
            console.log('Salesforce auth data received:', authData);
            setShowSalesforceAuth(false);
            if (pendingService) {
              // Mark service as authenticated
              // CrmNavigator will automatically show SalesforceDashboard based on selectedService
              setAuthenticatedServices(prev => new Set([...prev, pendingService]));
              dispatch(setSelectedService(pendingService));
              setPendingService(null);
            }
          }}
          onAuthError={(error) => {
            console.error('Salesforce auth error:', error);
            setShowSalesforceAuth(false);
            setPendingService(null);
          }}
          onClose={() => {
            setShowSalesforceAuth(false);
            setPendingService(null);
          }}
        />
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1 },
  sep: { height: 1, opacity: 0.6 },
  serviceItem: {
    marginVertical: 4,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 12,
    justifyContent: 'space-between',
  },
  disabledRow: {
    opacity: 0.6,
  },
  mainServiceButton: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  iconCircle: {
    width: 36,
    height: 36,
    borderRadius: 8,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: 12,
  },
  title: { 
    fontSize: 14,
    flex: 1,
  },
  loadingContainer: {
    marginLeft: 8,
  },
  loadingText: {
    fontSize: 12,
    fontStyle: 'italic',
  },
  reauthButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 8,
    paddingVertical: 6,
    borderRadius: 6,
    borderWidth: 1,
    marginLeft: 8,
  },
  reauthText: {
    fontSize: 11,
    marginLeft: 4,
  },
});

export default IntegrationCategoryScreen;


