import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { SubtaskData } from '@/types';
import { PRIORITY_COLORS } from '@/constants';
import { useSettings } from '@/theme';
import Svg, { Path } from 'react-native-svg';

interface SubtaskItemProps {
  subtask: SubtaskData;
  onToggle: () => void;
}

export function SubtaskItem({ subtask, onToggle }: SubtaskItemProps) {
  const { theme } = useSettings();

  return (
    <View style={[styles.container, { backgroundColor: theme.cardAlt }]}>
      <TouchableOpacity
        style={styles.checkCircle}
        onPress={onToggle}
        activeOpacity={0.7}
        accessibilityLabel={subtask.completed ? 'Mark incomplete' : 'Mark complete'}
      >
        <Svg width={20} height={20} viewBox="0 0 24 24">
          {subtask.completed ? (
            <>
              <Path
                d="M20 6L9 17l-5-5"
                stroke={theme.accent}
                strokeWidth={2.5}
                strokeLinecap="round"
                strokeLinejoin="round"
                fill="none"
              />
            </>
          ) : (
            <Path
              d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2"
              stroke={theme.borderStrong}
              strokeWidth={2}
              fill="none"
            />
          )}
        </Svg>
      </TouchableOpacity>

      <Text
        style={[
          styles.title,
          { color: theme.text },
          subtask.completed && styles.titleCompleted,
        ]}
        numberOfLines={1}
      >
        {subtask.title}
      </Text>

      {subtask.priority && subtask.priority !== 'none' && (
        <View style={[styles.priorityBadge, { backgroundColor: PRIORITY_COLORS[subtask.priority] }]}>
          <Text style={styles.priorityText}>{subtask.priority.charAt(0).toUpperCase()}</Text>
        </View>
      )}

      {subtask.dueDate && subtask.dueDate > 0 && (
        <Text style={[styles.dueText, { color: theme.textFaint }]} numberOfLines={1}>
          {formatDueDate(subtask.dueDate, subtask.dueTime, subtask.endTime || '')}
        </Text>
      )}
    </View>
  );
}

function formatDueDate(dueDate: number, dueTime: string, endTime?: string): string {
  const date = new Date(dueDate);
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1);

  let dateStr = '';
  if (date.toDateString() === today.toDateString()) {
    dateStr = 'Today';
  } else if (date.toDateString() === tomorrow.toDateString()) {
    dateStr = 'Tomorrow';
  } else {
    dateStr = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
  }

  if (dueTime && endTime) {
    return `${dateStr} · ${formatTime12(dueTime)} – ${formatTime12(endTime)}`;
  }
  return dueTime ? `${dateStr} at ${formatTime12(dueTime)}` : dateStr;
}

function formatTime12(time: string): string {
  const [hours, minutes] = time.split(':').map(Number);
  if (Number.isNaN(hours) || Number.isNaN(minutes)) return time;
  const period = hours >= 12 ? 'PM' : 'AM';
  const h = hours % 12 === 0 ? 12 : hours % 12;
  return `${h}:${String(minutes).padStart(2, '0')} ${period}`;
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    paddingHorizontal: 12,
    paddingVertical: 10,
    borderRadius: 10,
    marginLeft: 32,
    marginBottom: 4,
  },
  checkCircle: {
    width: 20,
    height: 20,
    borderRadius: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: 14,
    flex: 1,
  },
  titleCompleted: {
    textDecorationLine: 'line-through',
    color: '#9E9E9E',
  },
  priorityBadge: {
    paddingHorizontal: 5,
    paddingVertical: 1,
    borderRadius: 6,
    minWidth: 18,
    alignItems: 'center',
  },
  priorityText: {
    fontSize: 8,
    fontWeight: '700',
    color: '#FFFFFF',
  },
  dueText: {
    fontSize: 12,
    maxWidth: '30%',
  },
});
