import React, { useState } from 'react';
import { Modal, View, Text, StyleSheet, TextInput, TouchableOpacity, ScrollView, KeyboardAvoidingView, Platform, Pressable } from 'react-native';
import Category from '@/models/Category';
import { useSettings } from '@/theme';
import { CATEGORY_COLORS } from '@/constants';
import { createCategory, updateCategory, deleteCategory } from '@/utils/categoryActions';
import { confirmAction } from '@/utils/confirm';
import ColorPickerInput from '@/components/ColorPickerInput';
import Svg, { Path } from 'react-native-svg';

interface CategoryEditorModalProps {
  visible: boolean;
  category: Category | null;
  categoryCount: number;
  onClose: () => void;
}

export function CategoryEditorModal({ visible, category, categoryCount, onClose }: CategoryEditorModalProps) {
  const { theme } = useSettings();
  const [name, setName] = useState('');
  const [color, setColor] = useState(CATEGORY_COLORS[0]);
  const [prevVisible, setPrevVisible] = useState(visible);

  if (prevVisible !== visible) {
    setPrevVisible(visible);
    if (visible) {
      setName(category?.name ?? '');
      setColor(category?.color ?? CATEGORY_COLORS[0]);
    }
  }

  const canDelete = category !== null && categoryCount > 1;

  const handleSave = async () => {
    const trimmed = name.trim();
    if (!trimmed) return;
    if (category) {
      await updateCategory(category.id, trimmed, color);
    } else {
      await createCategory(trimmed, color);
    }
    onClose();
  };

  const handleDelete = () => {
    if (!category || !canDelete) return;
    confirmAction({
      title: 'Delete Category',
      message: `Tasks in "${category.name}" will be moved to another category.`,
      confirmLabel: 'Delete',
      destructive: true,
      onConfirm: async () => {
        await deleteCategory(category.id);
        onClose();
      },
    });
  };

  return (
    <Modal visible={visible} transparent animationType="fade" onRequestClose={onClose}>
      <KeyboardAvoidingView
        style={styles.fill}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      >
        <Pressable
          style={styles.overlay}
          onPress={onClose}
          accessibilityRole="none"
        >
          <Pressable
            style={[styles.sheet, { backgroundColor: theme.sheetBg }]}
            onPress={() => {}}
          >
            <ScrollView
              showsVerticalScrollIndicator={false}
              keyboardShouldPersistTaps="handled"
            >
              <View style={styles.header}>
                <Text style={[styles.title, { color: theme.text }]}>
                  {category ? 'Edit Category' : 'New Category'}
                </Text>
                <TouchableOpacity onPress={onClose} style={styles.closeButton} hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }} accessibilityRole="button" accessibilityLabel="Close category editor">
                  <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.label, { color: theme.textSecondary }]}>Name</Text>
              <TextInput
                style={[
                  styles.input,
                  { backgroundColor: theme.inputBg, borderColor: theme.borderStrong, color: theme.text },
                ]}
                placeholder="Category name"
                placeholderTextColor={theme.textMuted}
                value={name}
                onChangeText={setName}
                maxLength={30}
                autoFocus
                autoCapitalize="sentences"
              />

              <Text style={[styles.label, { color: theme.textSecondary }]}>Color</Text>
              <View style={styles.colorGrid}>
                {CATEGORY_COLORS.map((c) => (
                  <TouchableOpacity
                    key={c}
                    style={[
                      styles.colorOption,
                      { backgroundColor: c },
                      color === c && styles.colorOptionSelected,
                    ]}
                    onPress={() => setColor(c)}
                    activeOpacity={0.8}
                    accessibilityRole="radio"
                    accessibilityLabel={`Color ${c}`}
                    accessibilityState={{ selected: color === c }}
                  >
                    {color === c && (
                      <Svg width={16} height={16} viewBox="0 0 24 24">
                        <Path d="M5 12l5 5 9-10" stroke="#FFFFFF" strokeWidth={3} strokeLinecap="round" strokeLinejoin="round" fill="none" />
                      </Svg>
                    )}
                  </TouchableOpacity>
                ))}
              </View>
              <ColorPickerInput value={color} onChange={setColor} />

              <View style={styles.actions}>
                {category && (
                  <TouchableOpacity
                    style={[styles.deleteButton, { borderColor: theme.accentBorder }]}
                    onPress={handleDelete}
                    disabled={!canDelete}
                    activeOpacity={0.7}
                  >
                    <Text style={[styles.deleteButtonText, { color: canDelete ? theme.accent : theme.textMuted }]}>
                      Delete
                    </Text>
                  </TouchableOpacity>
                )}
                <TouchableOpacity
                  style={[styles.saveButton, { backgroundColor: theme.accent }, !name.trim() && styles.saveButtonDisabled]}
                  onPress={handleSave}
                  disabled={!name.trim()}
                  activeOpacity={0.8}
                >
                  <Text style={[styles.saveButtonText, { color: theme.accentText }]}>Save</Text>
                </TouchableOpacity>
              </View>
            </ScrollView>
          </Pressable>
        </Pressable>
      </KeyboardAvoidingView>
    </Modal>
  );
}

const styles = StyleSheet.create({
  fill: {
    flex: 1,
  },
  overlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.55)',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 24,
  },
  sheet: {
    width: '100%',
    maxWidth: 380,
    maxHeight: '100%',
    borderRadius: 16,
    padding: 20,
    gap: 8,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: 4,
  },
  title: {
    fontSize: 18,
    fontWeight: '700',
  },
  closeButton: {
    padding: 4,
  },
  label: {
    fontSize: 13,
    fontWeight: '600',
    marginTop: 8,
  },
  input: {
    height: 48,
    paddingHorizontal: 14,
    borderRadius: 12,
    borderWidth: 1,
    fontSize: 16,
  },
  colorGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 10,
    paddingVertical: 4,
  },
  colorOption: {
    width: 36,
    height: 36,
    borderRadius: 18,
    alignItems: 'center',
    justifyContent: 'center',
  },
  colorOptionSelected: {
    borderWidth: 2,
    borderColor: '#FFFFFF',
    shadowColor: '#000',
    shadowOpacity: 0.3,
    shadowRadius: 3,
    elevation: 3,
  },
  actions: {
    flexDirection: 'row',
    gap: 12,
    marginTop: 16,
  },
  deleteButton: {
    flex: 1,
    paddingVertical: 12,
    borderRadius: 12,
    borderWidth: 1,
    alignItems: 'center',
  },
  deleteButtonText: {
    fontSize: 15,
    fontWeight: '600',
  },
  saveButton: {
    flex: 1,
    paddingVertical: 12,
    borderRadius: 12,
    alignItems: 'center',
  },
  saveButtonDisabled: {
    opacity: 0.5,
  },
  saveButtonText: {
    fontSize: 15,
    fontWeight: '600',
  },
});
