/**
 * Task/checklist item for deals and TC workflows.
 */

import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { useTheme } from '../themes/ThemeProvider';

export interface Task {
  id: number;
  title: string;
  description?: string;
  status: 'pending' | 'in_progress' | 'completed' | 'overdue';
  due_date: string | null;
  assigned_to: string | null;
  priority: 'low' | 'normal' | 'high' | 'critical';
  phase?: number;
}

interface TaskItemProps {
  task: Task;
  onToggle: (task: Task) => void;
  onPress: (task: Task) => void;
}

export default function TaskItem({ task, onToggle, onPress }: TaskItemProps) {
  const { theme } = useTheme();
  const isComplete = task.status === 'completed';
  const isOverdue = task.status === 'overdue';

  const priorityColors: Record<string, string> = {
    low: theme.colors.textSecondary,
    normal: theme.colors.info,
    high: theme.colors.warning,
    critical: theme.colors.error,
  };

  const formatDate = (date: string | null): string => {
    if (!date) return '';
    try {
      const d = new Date(date);
      return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
    } catch {
      return date;
    }
  };

  return (
    <TouchableOpacity
      style={[styles.container, { backgroundColor: theme.colors.card }]}
      onPress={() => onPress(task)}
      activeOpacity={0.7}
    >
      <TouchableOpacity
        style={[
          styles.checkbox,
          {
            borderColor: isComplete ? theme.colors.success : theme.colors.border,
            backgroundColor: isComplete ? theme.colors.success : 'transparent',
          },
        ]}
        onPress={() => onToggle(task)}
        hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
      >
        {isComplete && <Text style={styles.checkmark}>✓</Text>}
      </TouchableOpacity>

      <View style={styles.content}>
        <View style={styles.titleRow}>
          <Text
            style={[
              styles.title,
              { color: theme.colors.text },
              isComplete && styles.titleComplete,
            ]}
            numberOfLines={2}
          >
            {task.title}
          </Text>
          {task.priority !== 'normal' && (
            <View
              style={[
                styles.priorityBadge,
                { backgroundColor: priorityColors[task.priority] + '20' },
              ]}
            >
              <Text style={[styles.priorityText, { color: priorityColors[task.priority] }]}>
                {task.priority.toUpperCase()}
              </Text>
            </View>
          )}
        </View>

        <View style={styles.metaRow}>
          {task.due_date && (
            <Text
              style={[
                styles.dueDate,
                { color: isOverdue ? theme.colors.error : theme.colors.textSecondary },
                isOverdue && styles.overdue,
              ]}
            >
              {isOverdue ? 'OVERDUE: ' : 'Due: '}
              {formatDate(task.due_date)}
            </Text>
          )}
          {task.assigned_to && (
            <Text style={[styles.assigned, { color: theme.colors.textSecondary }]}>
              {task.assigned_to}
            </Text>
          )}
        </View>
      </View>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#E5E7EB',
  },
  checkbox: {
    width: 24,
    height: 24,
    borderRadius: 6,
    borderWidth: 2,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
    marginTop: 2,
  },
  checkmark: {
    color: '#FFF',
    fontSize: 14,
    fontWeight: '700',
  },
  content: {
    flex: 1,
  },
  titleRow: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    justifyContent: 'space-between',
  },
  title: {
    fontSize: 15,
    fontWeight: '500',
    flex: 1,
    marginRight: 8,
  },
  titleComplete: {
    textDecorationLine: 'line-through',
    opacity: 0.5,
  },
  priorityBadge: {
    paddingHorizontal: 6,
    paddingVertical: 2,
    borderRadius: 4,
  },
  priorityText: {
    fontSize: 10,
    fontWeight: '700',
  },
  metaRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 4,
    gap: 12,
  },
  dueDate: {
    fontSize: 12,
  },
  overdue: {
    fontWeight: '600',
  },
  assigned: {
    fontSize: 12,
  },
});
