import React, { useState, useEffect, useMemo, useRef } from 'react';
import { View, StyleSheet, TextInput, TouchableOpacity, Keyboard, Text } from 'react-native';
import { database, collections } from '@/database';
import { useCategories } from '@/hooks/useDatabase';
import { useSettings } from '@/theme';
import { OptionPickerModal } from '@/components/OptionPickerModal';
import { tagsToString } from '@/types';
import Svg, { Path } from 'react-native-svg';
import { subscribeToQuickAdd } from '@/utils/quickAddFocus';

interface QuickAddBarProps {
  dueDate?: number;
  placeholder?: string;
}

export function QuickAddBar({ dueDate = 0, placeholder }: QuickAddBarProps) {
  const { theme, defaultCategoryId } = useSettings();
  const categories = useCategories();
  const [title, setTitle] = useState('');
  const [categoryId, setCategoryId] = useState(() => defaultCategoryId || '');
  const [categoryPickerVisible, setCategoryPickerVisible] = useState(false);
  const inputRef = useRef<TextInput>(null);

  const visibleCategories = useMemo(
    () => categories.filter((c) => c.name.toLowerCase() !== 'calendar'),
    [categories]
  );
  const categoryColor = visibleCategories.find((c) => c.id === categoryId)?.color ?? '#9E9E9E';

  useEffect(() => {
    return subscribeToQuickAdd(() => {
      setTimeout(() => {
        inputRef.current?.focus();
      }, 100);
    });
  }, []);

  const handleAdd = async () => {
    const trimmed = title.trim();
    if (!trimmed) return;

    const now = new Date();
    await database.write(async () => {
      await collections.tasks.create((t) => {
        t.title = trimmed;
        t.description = '';
        t.categoryId = categoryId || '';
        t.tags = tagsToString(categoryId ? [categoryId] : []);
        t.priority = 'none';
        t.completed = false;
        t.dueDate = dueDate;
        t.dueTime = '';
        t.endTime = '';
        t.repeat = 'none';
        t.repeatInterval = 1;
        t.repeatDays = '';
        t.reminder = 'none';
        t.seriesId = '';
        t.createdAt = now;
        t.updatedAt = now;
      });
    });
    setTitle('');
    Keyboard.dismiss();
  };

  return (
    <View style={styles.wrapper}>
      <View style={[styles.bar, { backgroundColor: theme.card, borderColor: theme.border }]}>
        <TouchableOpacity
          style={[styles.categoryButton, { borderColor: theme.borderStrong, backgroundColor: theme.cardAlt }]}
          onPress={() => setCategoryPickerVisible(true)}
          activeOpacity={0.7}
          accessibilityLabel="Select category"
        >
          <View style={[styles.categoryButtonDot, { backgroundColor: categoryColor }]} />
          <Svg width={12} height={12} viewBox="0 0 24 24">
            <Path d="M6 9l6 6 6-6" stroke={theme.textSecondary} strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round" fill="none" />
          </Svg>
        </TouchableOpacity>
        <TextInput
          ref={inputRef}
          style={[styles.input, { color: theme.text }]}
          placeholder={placeholder ?? 'Add a task'}
          placeholderTextColor={theme.textMuted}
          value={title}
          onChangeText={setTitle}
          onSubmitEditing={handleAdd}
          returnKeyType="done"
          accessibilityLabel="Quick add task"
          accessibilityHint="Enter a task name and press the add button"
        />
        <TouchableOpacity
          style={[styles.submit, { backgroundColor: theme.accent }, title.trim() ? {} : styles.submitDisabled]}
          onPress={title.trim() ? handleAdd : undefined}
          disabled={!title.trim()}
          activeOpacity={0.8}
          accessibilityLabel="Add task"
          accessibilityHint="Adds the entered task to the list"
          accessibilityState={{ disabled: !title.trim() }}
        >
          <View style={styles.submitLabelRow}>
            <Text style={[styles.submitText, { color: theme.accentText }]}>Add a Task</Text>
            <Svg width={18} height={18} viewBox="0 0 24 24">
              <Path
                d="M12 5v14M12 5l-5 5M12 5l5 5"
                stroke={theme.accentText}
                strokeWidth={2.5}
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </Svg>
          </View>
        </TouchableOpacity>
      </View>

      <OptionPickerModal
        visible={categoryPickerVisible}
        title="Select Category"
        options={[{ value: '', label: 'None', color: '#9E9E9E' }, ...visibleCategories.map((c) => ({ value: c.id, label: c.name, color: c.color }))]}
        selectedValue={categoryId}
        onSelect={(value) => setCategoryId(Array.isArray(value) ? value[0] : value)}
        onClose={() => setCategoryPickerVisible(false)}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  wrapper: {
    paddingHorizontal: 8,
    paddingTop: 4,
  },
  bar: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    paddingHorizontal: 8,
    paddingVertical: 8,
    borderRadius: 14,
    borderWidth: 1,
    borderBottomWidth: 1,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: -2 },
    shadowOpacity: 0.10,
    shadowRadius: 6,
    elevation: 6,
  },
  categoryButton: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 3,
    paddingVertical: 6,
    paddingHorizontal: 6,
    borderRadius: 10,
    borderWidth: 1,
    height: 40,
  },
  categoryButtonDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
  },
  input: {
    flex: 1,
    fontSize: 15,
    paddingVertical: 10,
    minHeight: 40,
  },
  submit: {
    minWidth: 88,
    height: 40,
    paddingHorizontal: 12,
    borderRadius: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  submitLabelRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
  },
  submitText: {
    fontSize: 13,
    fontWeight: '700',
  },
  submitDisabled: {
    opacity: 0.5,
  },
});