import { Stack, useFocusEffect } from 'expo-router';
import { useCallback, useState } from 'react';
import { Pressable, ScrollView, StyleSheet, TextInput, View } from 'react-native';

import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import { MaxContentWidth, Spacing } from '@/constants/theme';
import { useTheme } from '@/hooks/use-theme';
import { useCourses } from '@/stores/coursesStore';

export default function CoursesScreen() {
  const theme = useTheme();
  const { items, refresh, createCourse, rename, remove } = useCourses();
  const [name, setName] = useState('');
  const [editing, setEditing] = useState<string | null>(null);
  const [editName, setEditName] = useState('');

  useFocusEffect(
    useCallback(() => {
      void refresh();
    }, [refresh]),
  );

  const add = async () => {
    const n = name.trim();
    if (!n) return;
    await createCourse({ name: n });
    setName('');
  };

  return (
    <ThemedView style={styles.fill}>
      <Stack.Screen options={{ title: 'Courses' }} />
      <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
        <ThemedText type="small" themeColor="textSecondary">
          Group lectures by course. Deleting a course moves its transcripts to Unsorted (nothing is lost).
        </ThemedText>

        <View style={styles.row}>
          <TextInput
            value={name}
            onChangeText={setName}
            placeholder="New course name"
            placeholderTextColor={theme.textSecondary}
            style={[styles.input, styles.flex, { color: theme.text, backgroundColor: theme.backgroundElement }]}
          />
          <Pressable onPress={() => void add()} style={[styles.addBtn, { opacity: name.trim() ? 1 : 0.5 }]}>
            <ThemedText style={styles.white}>Add</ThemedText>
          </Pressable>
        </View>

        {items.length === 0 && (
          <ThemedText type="small" themeColor="textSecondary" style={styles.pad}>No courses yet.</ThemedText>
        )}

        {items.map((c) => (
          <ThemedView key={c.id} type="backgroundElement" style={styles.card}>
            {editing === c.id ? (
              <View style={styles.row}>
                <TextInput
                  value={editName}
                  onChangeText={setEditName}
                  autoFocus
                  style={[styles.input, styles.flex, { color: theme.text, backgroundColor: theme.background }]}
                />
                <Pressable
                  onPress={async () => {
                    if (editName.trim()) await rename(c.id, editName.trim());
                    setEditing(null);
                  }}
                  style={styles.addBtn}>
                  <ThemedText style={styles.white}>Save</ThemedText>
                </Pressable>
              </View>
            ) : (
              <View style={styles.rowBetween}>
                <ThemedText type="smallBold" style={styles.flex} numberOfLines={1}>{c.name}</ThemedText>
                <View style={styles.actions}>
                  <Pressable
                    onPress={() => {
                      setEditing(c.id);
                      setEditName(c.name);
                    }}
                    hitSlop={8}>
                    <ThemedText type="small" themeColor="textSecondary">Rename</ThemedText>
                  </Pressable>
                  <Pressable onPress={() => void remove(c.id)} hitSlop={8}>
                    <ThemedText type="small" themeColor="textSecondary">Delete</ThemedText>
                  </Pressable>
                </View>
              </View>
            )}
          </ThemedView>
        ))}
      </ScrollView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  fill: { flex: 1 },
  content: { padding: Spacing.three, gap: Spacing.two, maxWidth: MaxContentWidth, width: '100%', alignSelf: 'center' },
  row: { flexDirection: 'row', gap: Spacing.two, alignItems: 'center' },
  rowBetween: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: Spacing.two },
  flex: { flex: 1 },
  input: { borderRadius: Spacing.two, paddingHorizontal: Spacing.three, paddingVertical: Spacing.two, fontSize: 15 },
  addBtn: { backgroundColor: '#3c87f7', paddingHorizontal: Spacing.three, paddingVertical: Spacing.two, borderRadius: Spacing.two },
  white: { color: '#fff', fontWeight: '700' },
  card: { padding: Spacing.three, borderRadius: Spacing.three },
  actions: { flexDirection: 'row', gap: Spacing.three },
  pad: { paddingVertical: Spacing.four, textAlign: 'center' },
});
