import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, KeyboardAvoidingView, Platform } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { database, collections } from '@/database';
import { useCategories } from '@/hooks/useDatabase';
import { useSettings } from '@/theme';
import { OptionPickerModal } from '@/components/OptionPickerModal';
import Svg, { Path } from 'react-native-svg';

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

export function QuickAddBar({ dueDate = 0, placeholder }: QuickAddBarProps) {
  const { theme, defaultCategoryId } = useSettings();
  const insets = useSafeAreaInsets();
  const categories = useCategories();
  const [title, setTitle] = useState('');
  const [categoryId, setCategoryId] = useState(defaultCategoryId || categories[0]?.id || '');
  const [categoryPickerVisible, setCategoryPickerVisible] = useState(false);

  const categoryColor = categories.find((c) => c.id === categoryId)?.color ?? '#9E9E9E';

  useEffect(() => {
    if (!categoryId) {
      setCategoryId(defaultCategoryId || categories[0]?.id || '');
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [categories, defaultCategoryId]);

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

    const now = new Date();
    await database.write(async () => {
      await collections.tasks.create((t) => {
        t.title = trimmed;
        t.description = '';
        t.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('');
  };

  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      style={[styles.wrapper, { bottom: insets.bottom + 16 }]}
    >
      <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.textFaint} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" fill="none" />
          </Svg>
        </TouchableOpacity>
        <TextInput
          style={[styles.input, { color: theme.text }]}
          placeholder={placeholder ?? 'Add a task'}
          placeholderTextColor={theme.textMuted}
          value={title}
          onChangeText={setTitle}
          onSubmitEditing={handleAdd}
          returnKeyType="done"
        />
        <TouchableOpacity
          style={[styles.submit, { backgroundColor: theme.accent }, !title.trim() && styles.submitDisabled]}
          onPress={handleAdd}
          disabled={!title.trim()}
          activeOpacity={0.8}
          accessibilityLabel="Add task"
        >
          <Svg width={20} height={20} viewBox="0 0 24 24">
            <Path
              d="M12 5v14M5 12h14"
              stroke="#FFFFFF"
              strokeWidth={2.5}
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </Svg>
        </TouchableOpacity>
      </View>

      <OptionPickerModal
        visible={categoryPickerVisible}
        title="Select Category"
        options={categories.map((c) => ({ value: c.id, label: c.name, color: c.color }))}
        selectedValue={categoryId}
        onSelect={(value) => setCategoryId(value)}
        onClose={() => setCategoryPickerVisible(false)}
      />
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  wrapper: {
    position: 'absolute',
    left: 16,
    right: 16,
    bottom: 24,
  },
  bar: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 10,
    paddingHorizontal: 10,
    paddingVertical: 10,
    borderRadius: 16,
    borderWidth: 1,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.12,
    shadowRadius: 12,
    elevation: 8,
  },
  categoryButton: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    paddingVertical: 10,
    paddingHorizontal: 12,
    borderRadius: 12,
    borderWidth: 1,
  },
  categoryButtonDot: {
    width: 12,
    height: 12,
    borderRadius: 6,
  },
  input: {
    flex: 1,
    fontSize: 15,
    paddingVertical: 10,
  },
  submit: {
    width: 40,
    height: 40,
    borderRadius: 12,
    alignItems: 'center',
    justifyContent: 'center',
  },
  submitDisabled: {
    opacity: 0.5,
  },
});
