import { router } from 'expo-router';
import { SymbolView } from 'expo-symbols';
import { useRef, useState } from 'react';
import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
import Animated, { FadeIn } from 'react-native-reanimated';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import { Fonts, Spacing } from '@/constants/theme';
import { tasks } from '@/data/task-repository';
import { PopButton } from '@/design/pop-button';
import { TITLE_MAX_LENGTH } from '@/domain/glide';
import { useColorScheme } from '@/hooks/use-color-scheme';
import { useTheme } from '@/hooks/use-theme';
import { completionHaptic, selectionHaptic } from '@/lib/haptics';

const ROUNDED = Fonts?.rounded;

/**
 * Capture, distilled to one field. A task is just a title — no priority, no
 * effort, no resistance to declare. Everything else emerges from the swipe loop.
 * Add as many as you like in a row, then close.
 */
export function CreateTaskScreen() {
  const palette = useTheme();
  const scheme = useColorScheme();
  const insets = useSafeAreaInsets();
  const shadowColor = scheme === 'dark' ? 'rgba(0,0,0,0.55)' : palette.border;

  const inputRef = useRef<TextInput>(null);
  const [text, setText] = useState('');
  const [addedCount, setAddedCount] = useState(0);

  const canAdd = text.trim().length > 0;

  const submit = () => {
    const title = text.trim();
    if (title.length === 0) return;
    completionHaptic();
    tasks.createTask(title);
    setText('');
    setAddedCount((count) => count + 1);
    inputRef.current?.focus();
  };

  const close = () => router.back();

  return (
    <View style={[styles.root, { backgroundColor: palette.background }]}>
      <View
        style={[
          styles.content,
          { paddingTop: insets.top + Spacing.three, paddingBottom: insets.bottom + Spacing.three },
        ]}>
        <View style={styles.header}>
          <Text style={[styles.title, { color: palette.text }]}>New task</Text>
          <Pressable
            accessibilityRole="button"
            accessibilityLabel="Close"
            hitSlop={12}
            onPressIn={selectionHaptic}
            onPress={close}
            style={[styles.close, { backgroundColor: palette.surface, borderColor: palette.border }]}>
            <SymbolView name="xmark" size={16} tintColor={palette.text} weight="bold" fallback={null} />
          </Pressable>
        </View>

        <TextInput
          ref={inputRef}
          value={text}
          onChangeText={setText}
          placeholder="What needs doing?"
          placeholderTextColor={palette.textMuted}
          autoFocus
          maxLength={TITLE_MAX_LENGTH}
          returnKeyType="done"
          submitBehavior="submit"
          onSubmitEditing={submit}
          style={[
            styles.input,
            {
              backgroundColor: palette.surface,
              borderColor: palette.border,
              color: palette.text,
              boxShadow: `5px 6px 0 ${shadowColor}`,
            },
          ]}
          multiline
        />

        {/* Add sits directly under the field so it stays clear of the keyboard. */}
        <PopButton
          label="Add"
          symbol="plus"
          background={palette.accent}
          textColor="#FFFFFF"
          shadowColor={shadowColor}
          borderColor={palette.border}
          disabled={!canAdd}
          onPress={submit}
          style={styles.addButton}
        />

        {addedCount > 0 ? (
          <Animated.View
            key={addedCount}
            entering={FadeIn.duration(180)}
            style={[styles.added, { backgroundColor: palette.clearSoft, borderColor: palette.border }]}>
            <Text style={[styles.addedText, { color: palette.clear }]}>✓ {addedCount} added</Text>
          </Animated.View>
        ) : null}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  root: { flex: 1 },
  content: {
    flex: 1,
    paddingHorizontal: Spacing.four,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingBottom: Spacing.four,
  },
  title: {
    fontFamily: ROUNDED,
    fontSize: 28,
    fontWeight: '800',
    letterSpacing: -0.5,
  },
  close: {
    width: 38,
    height: 38,
    borderRadius: 999,
    borderWidth: 2.5,
    alignItems: 'center',
    justifyContent: 'center',
  },
  input: {
    minHeight: 120,
    borderRadius: 22,
    borderWidth: 3,
    padding: Spacing.four,
    fontFamily: ROUNDED,
    fontSize: 24,
    lineHeight: 30,
    fontWeight: '800',
    letterSpacing: -0.3,
  },
  addButton: {
    marginTop: Spacing.three,
  },
  added: {
    marginTop: Spacing.three,
    alignSelf: 'center',
    borderWidth: 2,
    borderRadius: 999,
    paddingHorizontal: 14,
    paddingVertical: 7,
  },
  addedText: {
    fontFamily: ROUNDED,
    fontSize: 13,
    fontWeight: '800',
  },
});
