import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { useTheme } from '@/shared/styles/useTheme';
import type { SalesforceEvent, SalesforceLead, SalesforceTask, SalesforceAccount, SalesforceOpportunity } from '../types/SalesforceCrmTypes';

interface BaseCardProps {
  onPress: () => void;
}

interface EventCardProps extends BaseCardProps {
  event: SalesforceEvent;
}

interface LeadCardProps extends BaseCardProps {
  lead: SalesforceLead;
}

interface TaskCardProps extends BaseCardProps {
  task: SalesforceTask;
}

interface AccountCardProps extends BaseCardProps {
  account: SalesforceAccount;
}

interface OpportunityCardProps extends BaseCardProps {
  opportunity: SalesforceOpportunity;
}

// Helper function to get status-based colors
const getStatusColor = (status: string, colors: any) => {
  switch (status.toLowerCase()) {
    case 'new':
    case 'open':
    case 'prospecting':
      return '#3AA0FF';
    case 'working':
    case 'in progress':
    case 'qualification':
    case 'needs analysis':
      return '#F59E0B';
    case 'qualified':
    case 'completed':
    case 'closed won':
      return '#22C55E';
    case 'unqualified':
    case 'closed lost':
      return '#EF4444';
    default:
      return colors.textLight;
  }
};

// Helper function to get priority-based colors
const getPriorityColor = (priority: string) => {
  switch (priority.toLowerCase()) {
    case 'high':
      return '#EF4444';
    case 'normal':
      return '#F59E0B';
    case 'low':
      return '#10B981';
    default:
      return '#6B7280';
  }
};

export const EventCard: React.FC<EventCardProps> = ({ event, onPress }) => {
  const { colors, fonts, shadows } = useTheme();

  return (
    <TouchableOpacity
      style={[styles.card, { backgroundColor: colors.surface, borderColor: colors.border, ...shadows.medium }]}
      onPress={onPress}
      activeOpacity={0.8}
    >
      <View style={styles.cardHeader}>
        <View style={styles.cardTitleRow}>
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.bold }]} numberOfLines={2}>
            {event.Subject}
          </Text>
          {event.IsAllDayEvent && (
            <View style={[styles.statusBadge, { backgroundColor: colors.primary }]}>
              <Text style={[styles.statusText, { color: colors.surface, fontFamily: fonts.medium }]}>
                All Day
              </Text>
            </View>
          )}
        </View>
        {event.Location && (
          <Text style={[styles.cardSubtitle, { color: colors.textLight, fontFamily: fonts.regular }]} numberOfLines={1}>
            {event.Location}
          </Text>
        )}
      </View>

      <View style={styles.cardContent}>
        {event.StartDateTime && (
          <View style={styles.infoRow}>
            <Icon name="calendar-start" size={16} color={colors.textLight} />
            <Text style={[styles.infoText, { color: colors.text, fontFamily: fonts.regular }]}>
              Start: {new Date(event.StartDateTime).toLocaleString()}
            </Text>
          </View>
        )}
        {event.EndDateTime && (
          <View style={styles.infoRow}>
            <Icon name="calendar-end" size={16} color={colors.textLight} />
            <Text style={[styles.infoText, { color: colors.text, fontFamily: fonts.regular }]}>
              End: {new Date(event.EndDateTime).toLocaleString()}
            </Text>
          </View>
        )}
        {event.Description && (
          <View style={styles.infoRow}>
            <Icon name="text" size={16} color={colors.textLight} />
            <Text style={[styles.infoText, { color: colors.text, fontFamily: fonts.regular }]} numberOfLines={2}>
              {event.Description}
            </Text>
          </View>
        )}
      </View>

      <View style={styles.cardFooter}>
        <Text style={[styles.dateText, { color: colors.textLight, fontFamily: fonts.regular }]}>
          Created: {new Date(event.CreatedDate).toLocaleDateString()}
        </Text>
      </View>
    </TouchableOpacity>
  );
};

export const LeadCard: React.FC<LeadCardProps> = ({ lead, onPress }) => {
  const { colors, fonts, shadows } = useTheme();

  return (
    <TouchableOpacity
      style={[styles.card, { backgroundColor: colors.surface, borderColor: colors.border, ...shadows.medium }]}
      onPress={onPress}
      activeOpacity={0.8}
    >
      <View style={styles.cardHeader}>
        <View style={styles.cardTitleRow}>
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.bold }]} numberOfLines={1}>
            {lead.FirstName} {lead.LastName}
          </Text>
          <View style={[styles.statusBadge, { backgroundColor: getStatusColor(lead.Status, colors) }]}>
            <Text style={[styles.statusText, { color: colors.surface, fontFamily: fonts.medium }]}>
              {lead.Status}
            </Text>
          </View>
        </View>
        <Text style={[styles.cardSubtitle, { color: colors.textLight, fontFamily: fonts.regular }]} numberOfLines={1}>
          {lead.Company}
        </Text>
      </View>

      <View style={styles.cardContent}>
        <View style={styles.infoRow}>
          <Icon name="email-outline" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.text, fontFamily: fonts.regular }]} numberOfLines={1}>
            {lead.Email}
          </Text>
        </View>
        {lead.Phone && (
          <View style={styles.infoRow}>
            <Icon name="phone-outline" size={16} color={colors.textLight} />
            <Text style={[styles.infoText, { color: colors.text, fontFamily: fonts.regular }]}>
              {lead.Phone}
            </Text>
          </View>
        )}
        {lead.Title && (
          <View style={styles.infoRow}>
            <Icon name="briefcase-outline" size={16} color={colors.textLight} />
            <Text style={[styles.infoText, { color: colors.text, fontFamily: fonts.regular }]}>
              {lead.Title}
            </Text>
          </View>
        )}
        {lead.LeadSource && (
          <View style={styles.infoRow}>
            <Icon name="source-branch" size={16} color={colors.textLight} />
            <Text style={[styles.infoText, { color: colors.text, fontFamily: fonts.regular }]}>
              Source: {lead.LeadSource}
            </Text>
          </View>
        )}
      </View>

      <View style={styles.cardFooter}>
        <Text style={[styles.dateText, { color: colors.textLight, fontFamily: fonts.regular }]}>
          Created: {lead.CreatedDate ? new Date(lead.CreatedDate).toLocaleDateString() : 'N/A'}
        </Text>
      </View>
    </TouchableOpacity>
  );
};

export const TaskCard: React.FC<TaskCardProps> = ({ task, onPress }) => {
  const { colors, fonts, shadows } = useTheme();

  return (
    <TouchableOpacity
      style={[styles.card, { backgroundColor: colors.surface, borderColor: colors.border, ...shadows.medium }]}
      onPress={onPress}
      activeOpacity={0.8}
    >
      <View style={styles.cardHeader}>
        <View style={styles.cardTitleRow}>
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.bold }]} numberOfLines={2}>
            {task.Subject}
          </Text>
          <View style={[styles.statusBadge, { backgroundColor: getStatusColor(task.Status, colors) }]}>
            <Text style={[styles.statusText, { color: colors.surface, fontFamily: fonts.medium }]}>
              {task.Status}
            </Text>
          </View>
        </View>
      </View>

      <View style={styles.cardContent}>
        {task.Description && (
          <Text style={[styles.descriptionText, { color: colors.text, fontFamily: fonts.regular }]} numberOfLines={2}>
            {task.Description}
          </Text>
        )}
        <View style={styles.infoRow}>
          <Icon name="flag-outline" size={16} color={getPriorityColor(task.Priority)} />
          <Text style={[styles.infoText, { color: colors.text, fontFamily: fonts.regular }]}>
            Priority: {task.Priority}
          </Text>
        </View>
        {task.ActivityDate && (
          <View style={styles.infoRow}>
            <Icon name="calendar-outline" size={16} color={colors.textLight} />
            <Text style={[styles.infoText, { color: colors.text, fontFamily: fonts.regular }]}>
              Due: {new Date(task.ActivityDate).toLocaleDateString()}
            </Text>
          </View>
        )}
      </View>

      <View style={styles.cardFooter}>
        <Text style={[styles.dateText, { color: colors.textLight, fontFamily: fonts.regular }]}>
          Created: {new Date(task.CreatedDate).toLocaleDateString()}
        </Text>
      </View>
    </TouchableOpacity>
  );
};

export const AccountCard: React.FC<AccountCardProps> = ({ account, onPress }) => {
  const { colors, fonts, shadows } = useTheme();

  return (
    <TouchableOpacity
      style={[styles.card, { backgroundColor: colors.surface, borderColor: colors.border, ...shadows.medium }]}
      onPress={onPress}
      activeOpacity={0.8}
    >
      <View style={styles.cardHeader}>
        <View style={styles.cardTitleRow}>
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.bold }]} numberOfLines={1}>
            {account.Name}
          </Text>
          {account.Type && (
            <View style={[styles.statusBadge, { backgroundColor: colors.primary }]}>
              <Text style={[styles.statusText, { color: colors.surface, fontFamily: fonts.medium }]}>
                {account.Type}
              </Text>
            </View>
          )}
        </View>
        {account.Industry && (
          <Text style={[styles.cardSubtitle, { color: colors.textLight, fontFamily: fonts.regular }]} numberOfLines={1}>
            {account.Industry}
          </Text>
        )}
      </View>

      <View style={styles.cardContent}>
        {account.Phone && (
          <View style={styles.infoRow}>
            <Icon name="phone-outline" size={16} color={colors.textLight} />
            <Text style={[styles.infoText, { color: colors.text, fontFamily: fonts.regular }]}>
              {account.Phone}
            </Text>
          </View>
        )}
        {account.Website && (
          <View style={styles.infoRow}>
            <Icon name="web" size={16} color={colors.textLight} />
            <Text style={[styles.infoText, { color: colors.text, fontFamily: fonts.regular }]} numberOfLines={1}>
              {account.Website}
            </Text>
          </View>
        )}
        {(account.BillingCity || account.BillingState) && (
          <View style={styles.infoRow}>
            <Icon name="map-marker-outline" size={16} color={colors.textLight} />
            <Text style={[styles.infoText, { color: colors.text, fontFamily: fonts.regular }]}>
              {[account.BillingCity, account.BillingState, account.BillingCountry].filter(Boolean).join(', ')}
            </Text>
          </View>
        )}
        {account.AnnualRevenue && (
          <View style={styles.infoRow}>
            <Icon name="currency-usd" size={16} color={colors.primary} />
            <Text style={[styles.infoText, { color: colors.primary, fontFamily: fonts.bold }]}>
              Revenue: ${account.AnnualRevenue.toLocaleString()}
            </Text>
          </View>
        )}
      </View>

      <View style={styles.cardFooter}>
        <Text style={[styles.dateText, { color: colors.textLight, fontFamily: fonts.regular }]}>
          Created: {new Date(account.CreatedDate).toLocaleDateString()}
        </Text>
      </View>
    </TouchableOpacity>
  );
};

export const OpportunityCard: React.FC<OpportunityCardProps> = ({ opportunity, onPress }) => {
  const { colors, fonts, shadows } = useTheme();

  return (
    <TouchableOpacity
      style={[styles.card, { backgroundColor: colors.surface, borderColor: colors.border, ...shadows.medium }]}
      onPress={onPress}
      activeOpacity={0.8}
    >
      <View style={styles.cardHeader}>
        <View style={styles.cardTitleRow}>
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.bold }]} numberOfLines={1}>
            {opportunity.Name}
          </Text>
          <View style={[styles.statusBadge, { backgroundColor: getStatusColor(opportunity.StageName, colors) }]}>
            <Text style={[styles.statusText, { color: colors.surface, fontFamily: fonts.medium }]}>
              {opportunity.StageName}
            </Text>
          </View>
        </View>
        {opportunity.Type && (
          <Text style={[styles.cardSubtitle, { color: colors.textLight, fontFamily: fonts.regular }]} numberOfLines={1}>
            {opportunity.Type}
          </Text>
        )}
      </View>

      <View style={styles.cardContent}>
        <View style={styles.infoRow}>
          <Icon name="currency-usd" size={16} color={colors.primary} />
          <Text style={[styles.infoText, { color: colors.primary, fontFamily: fonts.bold }]}>
            ${opportunity.Amount?.toLocaleString()}
          </Text>
        </View>
        <View style={styles.infoRow}>
          <Icon name="trending-up" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.text, fontFamily: fonts.regular }]}>
            Probability: {opportunity.Probability}%
          </Text>
        </View>
        <View style={styles.infoRow}>
          <Icon name="calendar-outline" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.text, fontFamily: fonts.regular }]}>
            Close date: {new Date(opportunity.CloseDate).toLocaleDateString()}
          </Text>
        </View>
        {opportunity.ForecastCategory && (
          <View style={styles.infoRow}>
            <Icon name="chart-line" size={16} color={colors.textLight} />
            <Text style={[styles.infoText, { color: colors.text, fontFamily: fonts.regular }]}>
              Forecast: {opportunity.ForecastCategory}
            </Text>
          </View>
        )}
      </View>

      <View style={styles.cardFooter}>
        <Text style={[styles.dateText, { color: colors.textLight, fontFamily: fonts.regular }]}>
          Created: {new Date(opportunity.CreatedDate).toLocaleDateString()}
        </Text>
      </View>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  card: {
    borderRadius: 12,
    borderWidth: 1,
    marginBottom: 16,
    overflow: 'hidden',
  },
  cardHeader: {
    padding: 16,
    paddingBottom: 12,
  },
  cardTitleRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginBottom: 4,
  },
  cardTitle: {
    fontSize: 16,
    flex: 1,
    marginRight: 8,
  },
  cardSubtitle: {
    fontSize: 14,
  },
  statusBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
  },
  statusText: {
    fontSize: 12,
  },
  cardContent: {
    paddingHorizontal: 16,
    paddingBottom: 12,
  },
  infoRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 6,
  },
  infoText: {
    marginLeft: 8,
    fontSize: 14,
    flex: 1,
  },
  descriptionText: {
    fontSize: 14,
    marginBottom: 8,
    lineHeight: 20,
  },
  cardFooter: {
    paddingHorizontal: 16,
    paddingVertical: 12,
    backgroundColor: '#F8F9FA',
  },
  dateText: {
    fontSize: 12,
  },
});

