import React, { useEffect, useState } from 'react';
import { Modal, View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { useSettings } from '@/theme';
import { TaskDeleteScope, getSeriesOccurrenceCounts } from '@/utils/taskActions';
import Svg, { Path } from 'react-native-svg';

interface TaskDeleteModalProps {
  visible: boolean;
  taskId: string | null;
  taskTitle?: string;
  isRepeating?: boolean;
  subtask?: boolean;
  onClose: () => void;
  onDelete: (scope: TaskDeleteScope) => void;
}

export function TaskDeleteModal({ visible, taskId, taskTitle, isRepeating, subtask, onClose, onDelete }: TaskDeleteModalProps) {
  const { theme } = useSettings();
  const [counts, setCounts] = useState({ future: 1, all: 1 });

  useEffect(() => {
    if (!visible || !taskId || subtask) return;
    let mounted = true;
    getSeriesOccurrenceCounts(taskId)
      .then((c) => {
        if (mounted) setCounts(c);
      })
      .catch(() => {});
    return () => { mounted = false; };
  }, [visible, taskId, subtask]);

  const options: { scope: TaskDeleteScope; label: string; hint?: string }[] = subtask
    ? [{ scope: 'this', label: 'This subtask only' }]
    : [{ scope: 'this', label: 'This task only' }];

  if (isRepeating) {
    options.push({ scope: 'future', label: 'This and future tasks', hint: counts.future > 1 ? `${counts.future} occurrences` : undefined });
    options.push({ scope: 'all', label: 'All tasks in series', hint: `${counts.all} occurrences` });
  }

  return (
    <Modal visible={visible} transparent animationType="fade" onRequestClose={onClose}>
      <View style={styles.overlay}>
        <View style={[styles.sheet, { backgroundColor: theme.sheetBg }]}>
          <View style={styles.header}>
            <Text style={[styles.title, { color: theme.text }]}>{subtask ? 'Delete Subtask' : 'Delete Task'}</Text>
            <TouchableOpacity onPress={onClose} style={styles.closeButton} hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}>
              <Svg width={18} height={18} viewBox="0 0 24 24">
                <Path d="M18 6L6 18M6 6l12 12" stroke={theme.textSecondary} strokeWidth={2.2} strokeLinecap="round" />
              </Svg>
            </TouchableOpacity>
          </View>
          <Text style={[styles.taskTitle, { color: theme.textSecondary }]} numberOfLines={1}>
            {taskTitle}
          </Text>
          {isRepeating ? (
            <Text style={[styles.hint, { color: theme.textMuted }]}>
              This task repeats. What would you like to delete?
            </Text>
          ) : (
            <Text style={[styles.hint, { color: theme.textMuted }]}>
              This action cannot be undone.
            </Text>
          )}

          <View style={styles.actions}>
            {options.map((option) => (
              <TouchableOpacity
                key={option.scope}
                style={[styles.actionButton, { borderColor: theme.accentBorder }]}
                onPress={() => onDelete(option.scope)}
                activeOpacity={0.7}
              >
                <Text style={[styles.actionLabel, { color: theme.accentStrong }]}>{option.label}</Text>
                {option.hint && <Text style={[styles.actionHint, { color: theme.textMuted }]}>{option.hint}</Text>}
              </TouchableOpacity>
            ))}
            <TouchableOpacity
              style={[styles.cancelButton, { borderColor: theme.borderStrong, backgroundColor: theme.card }]}
              onPress={onClose}
              activeOpacity={0.7}
            >
              <Text style={[styles.cancelLabel, { color: theme.textSecondary }]}>Cancel</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  overlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.4)',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 24,
  },
  sheet: {
    width: '100%',
    maxWidth: 380,
    borderRadius: 16,
    padding: 20,
    gap: 8,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  title: {
    fontSize: 18,
    fontWeight: '700',
  },
  closeButton: {
    padding: 4,
  },
  taskTitle: {
    fontSize: 14,
    fontWeight: '500',
  },
  hint: {
    fontSize: 13,
  },
  actions: {
    gap: 8,
    marginTop: 8,
  },
  actionButton: {
    paddingVertical: 12,
    paddingHorizontal: 14,
    borderRadius: 12,
    borderWidth: 1,
    alignItems: 'center',
    gap: 2,
  },
  actionLabel: {
    fontSize: 15,
    fontWeight: '600',
  },
  actionHint: {
    fontSize: 12,
  },
  cancelButton: {
    paddingVertical: 12,
    borderRadius: 12,
    borderWidth: 1,
    alignItems: 'center',
  },
  cancelLabel: {
    fontSize: 15,
    fontWeight: '600',
  },
});
