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 { 
  ZohoProject, 
  ZohoTask, 
  ZohoIssue, 
  ZohoPhase 
} from '../types/ZohoProjectsTypes';

// Project Card Component
interface ProjectCardProps {
  project: ZohoProject;
  onPress: () => void;
}

export const ProjectCard: React.FC<ProjectCardProps> = ({ project, onPress }) => {
  const { colors, fonts, spacing, shadows } = useTheme();

  const getStatusColor = (status: string) => {
    const statusColors: Record<string, string> = {
      'Active': '#10B981',
      'Completed': '#3B82F6',
      'On Hold': '#F59E0B',
      'Cancelled': '#EF4444',
      'Planning': '#8B5CF6',
    };
    return statusColors[status] || '#6B7280';
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
    });
  };

  return (
    <TouchableOpacity
      style={[styles.card, { backgroundColor: colors.surface, ...shadows.light }]}
      onPress={onPress}
      activeOpacity={0.8}
    >
      <View style={styles.cardHeader}>
        <View style={styles.titleContainer}>
          <Icon name="folder" size={20} color={colors.primary} />
          <Text style={[styles.title, { color: colors.text, fontFamily: fonts.medium }]}>
            {project.name}
          </Text>
        </View>
        <View
          style={[
            styles.statusBadge,
            { backgroundColor: getStatusColor(project.status?.name || 'Unknown') },
          ]}
        >
          <Text style={[styles.statusText, { color: colors.surface, fontFamily: fonts.medium }]}>
            {project.status?.name || 'Unknown'}
          </Text>
        </View>
      </View>

      <View style={styles.cardContent}>
        <View style={styles.infoRow}>
          <Icon name="account" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Owner: {project.owner?.full_name || project.owner?.name || 'Unknown'}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="tag" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Type: {project.project_type || 'Unknown'}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="calendar" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Start: {formatDate(project.start_date)}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="calendar-end" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            End: {formatDate(project.end_date)}
          </Text>
        </View>

        <View style={styles.progressContainer}>
          <View style={styles.progressInfo}>
            <Text style={[styles.progressLabel, { color: colors.text, fontFamily: fonts.medium }]}>
              Progress
            </Text>
            <Text style={[styles.progressValue, { color: colors.primary, fontFamily: fonts.bold }]}>
              {project.percent_complete || 0}%
            </Text>
          </View>
          <View style={[styles.progressBar, { backgroundColor: colors.background }]}>
            <View
              style={[
                styles.progressFill,
                {
                  width: `${project.percent_complete || 0}%`,
                  backgroundColor: colors.primary,
                },
              ]}
            />
          </View>
        </View>

        <View style={styles.statsRow}>
          <View style={styles.statItem}>
            <Icon name="check-circle" size={16} color="#10B981" />
            <Text style={[styles.statText, { color: colors.text, fontFamily: fonts.regular }]}>
              {project.tasks?.closed_count || 0} Tasks
            </Text>
          </View>
          <View style={styles.statItem}>
            <Icon name="alert-circle" size={16} color="#F59E0B" />
            <Text style={[styles.statText, { color: colors.text, fontFamily: fonts.regular }]}>
              {project.issues?.open_count || 0} Issues
            </Text>
          </View>
          <View style={styles.statItem}>
            <Icon name="flag" size={16} color="#3B82F6" />
            <Text style={[styles.statText, { color: colors.text, fontFamily: fonts.regular }]}>
              {project.milestones?.open_count || 0} Milestones
            </Text>
          </View>
        </View>
      </View>
    </TouchableOpacity>
  );
};

// Task Card Component
interface TaskCardProps {
  task: ZohoTask;
  onPress: () => void;
}

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

  const getPriorityColor = (priority: string) => {
    const priorityColors: Record<string, string> = {
      'high': '#EF4444',
      'urgent': '#DC2626',
      'medium': '#F59E0B',
      'low': '#10B981',
      'normal': '#3B82F6',
    };
    return priorityColors[priority?.toLowerCase()] || '#6B7280';
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
    });
  };

  return (
    <TouchableOpacity
      style={[styles.card, { backgroundColor: colors.surface, ...shadows.light }]}
      onPress={onPress}
      activeOpacity={0.8}
    >
      <View style={styles.cardHeader}>
        <View style={styles.titleContainer}>
          <Icon name="check-circle" size={20} color={colors.primary} />
          <Text style={[styles.title, { color: colors.text, fontFamily: fonts.medium }]}>
            {task.name}
          </Text>
        </View>
        <View
          style={[
            styles.priorityBadge,
            { backgroundColor: getPriorityColor(task.priority || 'normal') },
          ]}
        >
          <Text style={[styles.priorityText, { color: colors.surface, fontFamily: fonts.medium }]}>
            {task.priority?.toUpperCase() || 'NORMAL'}
          </Text>
        </View>
      </View>

      <View style={styles.cardContent}>
        <View style={styles.infoRow}>
          <Icon name="folder" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Project: {task.project?.name || 'Unknown'}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="account" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Owner: {task.owners_and_work?.owners?.[0]?.name || 'Unassigned'}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="calendar" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Due: {formatDate(task.end_date)}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="flag" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Status: {task.status?.name || 'Unknown'}
          </Text>
        </View>

        <View style={styles.progressContainer}>
          <View style={styles.progressInfo}>
            <Text style={[styles.progressLabel, { color: colors.text, fontFamily: fonts.medium }]}>
              Completion
            </Text>
            <Text style={[styles.progressValue, { color: colors.primary, fontFamily: fonts.bold }]}>
              {task.completion_percentage || 0}%
            </Text>
          </View>
          <View style={[styles.progressBar, { backgroundColor: colors.background }]}>
            <View
              style={[
                styles.progressFill,
                {
                  width: `${task.completion_percentage || 0}%`,
                  backgroundColor: colors.primary,
                },
              ]}
            />
          </View>
        </View>

        <View style={styles.statsRow}>
          <View style={styles.statItem}>
            <Icon name="clock" size={16} color="#3B82F6" />
            <Text style={[styles.statText, { color: colors.text, fontFamily: fonts.regular }]}>
              {task.duration?.value || '0h'}
            </Text>
          </View>
          <View style={styles.statItem}>
            <Icon name="currency-usd" size={16} color="#10B981" />
            <Text style={[styles.statText, { color: colors.text, fontFamily: fonts.regular }]}>
              {task.billing_type || 'Non-billable'}
            </Text>
          </View>
        </View>
      </View>
    </TouchableOpacity>
  );
};

// Issue Card Component
interface IssueCardProps {
  issue: ZohoIssue;
  onPress: () => void;
}

export const IssueCard: React.FC<IssueCardProps> = ({ issue, onPress }) => {
  const { colors, fonts, spacing, shadows } = useTheme();

  const getSeverityColor = (severity: string) => {
    const severityColors: Record<string, string> = {
      'Critical': '#DC2626',
      'High': '#EF4444',
      'Medium': '#F59E0B',
      'Low': '#10B981',
      'None': '#6B7280',
    };
    return severityColors[severity] || '#6B7280';
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
    });
  };

  return (
    <TouchableOpacity
      style={[styles.card, { backgroundColor: colors.surface, ...shadows.light }]}
      onPress={onPress}
      activeOpacity={0.8}
    >
      <View style={styles.cardHeader}>
        <View style={styles.titleContainer}>
          <Icon name="alert-circle" size={20} color={colors.primary} />
          <Text style={[styles.title, { color: colors.text, fontFamily: fonts.medium }]}>
            {issue.name}
          </Text>
        </View>
        <View
          style={[
            styles.severityBadge,
            { backgroundColor: getSeverityColor(issue.severity?.value || 'None') },
          ]}
        >
          <Text style={[styles.severityText, { color: colors.surface, fontFamily: fonts.medium }]}>
            {issue.severity?.value?.toUpperCase() || 'NONE'}
          </Text>
        </View>
      </View>

      <View style={styles.cardContent}>
        <View style={styles.infoRow}>
          <Icon name="folder" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Project: {issue.project?.name || 'Unknown'}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="account" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Assignee: {issue.assignee?.name || 'Unassigned'}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="calendar" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Created: {formatDate(issue.created_time)}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="flag" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Status: {issue.status?.name || 'Unknown'}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="tag" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Classification: {issue.classification?.value || 'Unknown'}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="cog" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Module: {issue.module?.value || 'Unknown'}
          </Text>
        </View>
      </View>
    </TouchableOpacity>
  );
};

// Phase Card Component
interface PhaseCardProps {
  phase: ZohoPhase;
  onPress: () => void;
}

export const PhaseCard: React.FC<PhaseCardProps> = ({ phase, onPress }) => {
  const { colors, fonts, spacing, shadows } = useTheme();

  const getStatusColor = (status: string) => {
    const statusColors: Record<string, string> = {
      'Active': '#10B981',
      'Completed': '#3B82F6',
      'On Hold': '#F59E0B',
      'Cancelled': '#EF4444',
      'Planning': '#8B5CF6',
    };
    return statusColors[status] || '#6B7280';
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
    });
  };

  return (
    <TouchableOpacity
      style={[styles.card, { backgroundColor: colors.surface, ...shadows.light }]}
      onPress={onPress}
      activeOpacity={0.8}
    >
      <View style={styles.cardHeader}>
        <View style={styles.titleContainer}>
          <Icon name="timeline" size={20} color={colors.primary} />
          <Text style={[styles.title, { color: colors.text, fontFamily: fonts.medium }]}>
            {phase.name}
          </Text>
        </View>
        <View
          style={[
            styles.statusBadge,
            { backgroundColor: getStatusColor(phase.status?.name || 'Unknown') },
          ]}
        >
          <Text style={[styles.statusText, { color: colors.surface, fontFamily: fonts.medium }]}>
            {phase.status?.name || 'Unknown'}
          </Text>
        </View>
      </View>

      <View style={styles.cardContent}>
        <View style={styles.infoRow}>
          <Icon name="folder" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Project: {phase.project?.name || 'Unknown'}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="account" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Owner: {`${phase.owner?.first_name} ${phase.owner?.last_name}` || 'Unknown'}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="calendar" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Start: {formatDate(phase.start_date)}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="calendar-end" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            End: {formatDate(phase.end_date)}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="tag" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Type: {phase.status_type || 'Unknown'}
          </Text>
        </View>

        <View style={styles.infoRow}>
          <Icon name="flag" size={16} color={colors.textLight} />
          <Text style={[styles.infoText, { color: colors.textLight, fontFamily: fonts.regular }]}>
            Flag: {phase.flag || 'None'}
          </Text>
        </View>
      </View>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  card: {
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
  },
  cardHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 12,
  },
  titleContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  title: {
    fontSize: 16,
    marginLeft: 8,
    flex: 1,
  },
  statusBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
  },
  statusText: {
    fontSize: 12,
  },
  priorityBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
  },
  priorityText: {
    fontSize: 12,
  },
  severityBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
  },
  severityText: {
    fontSize: 12,
  },
  cardContent: {
    gap: 8,
  },
  infoRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  infoText: {
    fontSize: 14,
    marginLeft: 8,
    flex: 1,
  },
  progressContainer: {
    marginTop: 8,
  },
  progressInfo: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 4,
  },
  progressLabel: {
    fontSize: 14,
  },
  progressValue: {
    fontSize: 14,
  },
  progressBar: {
    height: 6,
    borderRadius: 3,
    overflow: 'hidden',
  },
  progressFill: {
    height: '100%',
    borderRadius: 3,
  },
  statsRow: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginTop: 8,
    paddingTop: 8,
    borderTopWidth: 1,
    borderTopColor: '#E5E7EB',
  },
  statItem: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  statText: {
    fontSize: 12,
    marginLeft: 4,
  },
});
