import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Modal,
  Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { useTheme } from '@/shared/styles/useTheme';
import ZohoAuth from './ZohoAuth';

// Types
interface ZohoAuthData {
  accessToken: string;
  refreshToken?: string;
  expiresIn?: number;
  scope?: string;
  tokenType?: string;
}

const ZohoAuthExample: React.FC = () => {
  const { colors, spacing, fonts, shadows } = useTheme();
  const [showZohoAuth, setShowZohoAuth] = useState(false);
  const [authData, setAuthData] = useState<ZohoAuthData | null>(null);

  // Handle successful Zoho authentication
  const handleZohoAuthSuccess = (data: ZohoAuthData) => {
    console.log('Zoho Auth Success:', data);
    setAuthData(data);
    setShowZohoAuth(false);
    
    Alert.alert(
      'Authentication Successful',
      'You have successfully authenticated with Zoho!',
      [
        {
          text: 'OK',
          onPress: () => {
            // Here you would typically:
            // 1. Store the tokens securely
            // 2. Update your app state
            // 3. Navigate to the main app
            // 4. Make API calls to Zoho services
          },
        },
      ]
    );
  };

  // Handle Zoho authentication error
  const handleZohoAuthError = (error: string) => {
    console.error('Zoho Auth Error:', error);
    setShowZohoAuth(false);
    
    Alert.alert(
      'Authentication Failed',
      `Failed to authenticate with Zoho: ${error}`,
      [{ text: 'OK' }]
    );
  };

  // Handle closing the Zoho auth modal
  const handleCloseZohoAuth = () => {
    setShowZohoAuth(false);
  };

  // Handle Zoho login button press
  const handleZohoLogin = () => {
    setShowZohoAuth(true);
  };

  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <View style={[styles.content, { backgroundColor: colors.surface, ...shadows.medium }]}>
        {/* Header */}
        <View style={styles.header}>
          <Icon name="account-circle" size={32} color={colors.primary} />
          <Text style={[styles.title, { color: colors.text, fontFamily: fonts.bold }]}>
            Zoho Integration
          </Text>
          <Text style={[styles.subtitle, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Connect your Zoho account to access projects and data
          </Text>
        </View>

        {/* Auth Status */}
        {authData ? (
          <View style={[styles.statusContainer, { backgroundColor: colors.success + '20' }]}>
            <Icon name="check-circle" size={24} color={colors.success} />
            <Text style={[styles.statusText, { color: colors.success, fontFamily: fonts.medium }]}>
              Connected to Zoho
            </Text>
            <Text style={[styles.statusSubtext, { color: colors.textLight, fontFamily: fonts.regular }]}>
              Access Token: {authData.accessToken.substring(0, 20)}...
            </Text>
          </View>
        ) : (
          <View style={[styles.statusContainer, { backgroundColor: colors.warning + '20' }]}>
            <Icon name="warning" size={24} color={colors.warning} />
            <Text style={[styles.statusText, { color: colors.warning, fontFamily: fonts.medium }]}>
              Not Connected
            </Text>
            <Text style={[styles.statusSubtext, { color: colors.textLight, fontFamily: fonts.regular }]}>
              Connect your Zoho account to get started
            </Text>
          </View>
        )}

        {/* Zoho Login Button */}
        <TouchableOpacity
          style={[styles.zohoButton, { backgroundColor: colors.primary }]}
          onPress={handleZohoLogin}
          activeOpacity={0.8}
        >
          <Icon name="login" size={20} color={colors.surface} />
          <Text style={[styles.zohoButtonText, { color: colors.surface, fontFamily: fonts.medium }]}>
            {authData ? 'Reconnect to Zoho' : 'Connect to Zoho'}
          </Text>
        </TouchableOpacity>

        {/* Instructions */}
        <View style={styles.instructionsContainer}>
          <Text style={[styles.instructionsTitle, { color: colors.text, fontFamily: fonts.medium }]}>
            What you'll get access to:
          </Text>
          <View style={styles.featureList}>
            <View style={styles.featureItem}>
              <Icon name="check" size={16} color={colors.success} />
              <Text style={[styles.featureText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                Zoho Projects data and analytics
              </Text>
            </View>
            <View style={styles.featureItem}>
              <Icon name="check" size={16} color={colors.success} />
              <Text style={[styles.featureText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                Task and project management
              </Text>
            </View>
            <View style={styles.featureItem}>
              <Icon name="check" size={16} color={colors.success} />
              <Text style={[styles.featureText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                Time tracking and reporting
              </Text>
            </View>
            <View style={styles.featureItem}>
              <Icon name="check" size={16} color={colors.success} />
              <Text style={[styles.featureText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                Team collaboration insights
              </Text>
            </View>
          </View>
        </View>
      </View>

      {/* Zoho Auth Modal */}
      <Modal
        visible={showZohoAuth}
        animationType="slide"
        presentationStyle="fullScreen"
        onRequestClose={handleCloseZohoAuth}
      >
        <ZohoAuth
          onAuthSuccess={handleZohoAuthSuccess}
          onAuthError={handleZohoAuthError}
          onClose={handleCloseZohoAuth}
        />
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
    justifyContent: 'center',
  },
  content: {
    borderRadius: 16,
    padding: 24,
  },
  header: {
    alignItems: 'center',
    marginBottom: 24,
  },
  title: {
    fontSize: 24,
    marginTop: 12,
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 14,
    textAlign: 'center',
    lineHeight: 20,
  },
  statusContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    borderRadius: 12,
    marginBottom: 24,
  },
  statusText: {
    fontSize: 16,
    marginLeft: 8,
    flex: 1,
  },
  statusSubtext: {
    fontSize: 12,
    marginTop: 4,
  },
  zohoButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 16,
    borderRadius: 12,
    marginBottom: 24,
  },
  zohoButtonText: {
    fontSize: 16,
    marginLeft: 8,
  },
  instructionsContainer: {
    marginTop: 8,
  },
  instructionsTitle: {
    fontSize: 16,
    marginBottom: 12,
  },
  featureList: {
    gap: 8,
  },
  featureItem: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  featureText: {
    fontSize: 14,
    marginLeft: 8,
    flex: 1,
  },
});

export default ZohoAuthExample;
