import React from 'react';
import { View, TouchableOpacity, Text, StyleSheet } from 'react-native';
import { Swipeable } from 'react-native-gesture-handler';
import { useTodoState } from '../state';
import { colors, priorityColors } from '../theme';
import * as db from '../db';

export default function TodoItem({ todo }) {
  const { dispatch } = useTodoState();
  const { id, title, completed, category, priority } = todo;

  const handleToggle = () => {
    dispatch({ type: 'TOGGLE_TODO', id });
    db.toggleTodo(id, !completed).catch(err =>
      console.error('Toggle error:', err)
    );
  };

  const handleEdit = () => {
    dispatch({ type: 'SHOW_EDIT_FORM', todo });
  };

  const handleDelete = () => {
    dispatch({ type: 'DELETE_TODO', id });
    db.deleteTodo(id).catch(err => console.error('Delete error:', err));
  };

  const renderRightActions = () => (
    <TouchableOpacity onPress={handleDelete} style={styles.deleteButton}>
      <Text style={styles.deleteText}>Delete</Text>
    </TouchableOpacity>
  );

  return (
    <Swipeable renderRightActions={renderRightActions} overshootRight={false}>
      <TouchableOpacity
        onPress={handleEdit}
        activeOpacity={0.7}
        style={[
          styles.container,
          {
            backgroundColor: completed ? colors.completedBg : colors.surface,
          },
        ]}
      >
        <TouchableOpacity onPress={handleToggle} style={[
          styles.checkbox,
          {
            borderColor: completed ? colors.primary : colors.border,
            backgroundColor: completed ? colors.primary : 'transparent',
          },
        ]}>
          {completed && <Text style={styles.checkmark}>{'\u2713'}</Text>}
        </TouchableOpacity>

        <View style={styles.content}>
          <Text
            style={[
              styles.title,
              {
                color: completed ? colors.completedText : colors.onSurface,
                textDecorationLine: completed ? 'line-through' : 'none',
              },
            ]}
          >
            {title}
          </Text>
          <View style={styles.meta}>
            <View style={styles.categoryBadge}>
              <Text style={styles.categoryText}>{category}</Text>
            </View>
            <View
              style={[
                styles.priorityDot,
                {
                  backgroundColor:
                    priorityColors[priority] || '#999',
                },
              ]}
            />
          </View>
        </View>
      </TouchableOpacity>
    </Swipeable>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    marginHorizontal: 16,
    marginVertical: 4,
    padding: 16,
    borderRadius: 12,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
  },
  checkbox: {
    width: 28,
    height: 28,
    borderRadius: 14,
    borderWidth: 2,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  checkmark: {
    color: '#FFFFFF',
    fontSize: 16,
  },
  content: {
    flex: 1,
  },
  title: {
    fontSize: 16,
  },
  meta: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 4,
    gap: 8,
  },
  categoryBadge: {
    backgroundColor: '#E0E0E0',
    paddingHorizontal: 8,
    paddingVertical: 2,
    borderRadius: 10,
  },
  categoryText: {
    fontSize: 12,
    color: '#666666',
  },
  priorityDot: {
    width: 10,
    height: 10,
    borderRadius: 5,
  },
  deleteButton: {
    backgroundColor: '#B00020',
    justifyContent: 'center',
    alignItems: 'center',
    width: 80,
    borderRadius: 12,
    marginVertical: 4,
    marginRight: 16,
  },
  deleteText: {
    color: '#FFFFFF',
    fontWeight: 'bold',
    fontSize: 14,
  },
});
