// Modal shown before a transcription starts: capture title + course + lecture
// date + language so the recording lands organized (ROADMAP Phase 0).
import { useEffect, useState } from 'react';
import { Modal, Pressable, ScrollView, StyleSheet, TextInput, View } from 'react-native';

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

export interface PreCaptureResult {
  title: string;
  courseId: string | null;
  lectureDate?: number;
  language?: string;
}

interface Props {
  visible: boolean;
  defaultTitle: string;
  onStart: (r: PreCaptureResult) => void;
  onCancel: () => void;
}

function todayYmd(): string {
  const d = new Date();
  const pad = (n: number) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}

function parseYmd(s: string): number | undefined {
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s.trim());
  if (!m) return undefined;
  const t = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])).getTime();
  return Number.isFinite(t) ? t : undefined;
}

export function PreCaptureSheet({ visible, defaultTitle, onStart, onCancel }: Props) {
  const theme = useTheme();
  const courses = useCourses((s) => s.items);
  const refresh = useCourses((s) => s.refresh);
  const createCourse = useCourses((s) => s.createCourse);

  const [title, setTitle] = useState(defaultTitle);
  const [courseId, setCourseId] = useState<string | null>(null);
  const [dateStr, setDateStr] = useState(todayYmd());
  const [language, setLanguage] = useState('');
  const [newCourse, setNewCourse] = useState('');

  useEffect(() => {
    if (visible) {
      setTitle(defaultTitle);
      void refresh();
    }
  }, [visible, defaultTitle, refresh]);

  const addCourse = async () => {
    const name = newCourse.trim();
    if (!name) return;
    const c = await createCourse({ name });
    setCourseId(c.id);
    setNewCourse('');
  };

  const inputStyle = [styles.input, { color: theme.text, backgroundColor: theme.backgroundElement }];

  return (
    <Modal visible={visible} transparent animationType="slide" onRequestClose={onCancel}>
      <View style={styles.backdrop}>
        <ThemedView style={styles.sheet}>
          <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
            <ThemedText type="subtitle">New transcription</ThemedText>

            <ThemedText type="small" themeColor="textSecondary">Title</ThemedText>
            <TextInput
              value={title}
              onChangeText={setTitle}
              placeholder="Title"
              placeholderTextColor={theme.textSecondary}
              style={inputStyle}
            />

            <ThemedText type="small" themeColor="textSecondary">Course</ThemedText>
            <View style={styles.chips}>
              <Pressable
                onPress={() => setCourseId(null)}
                style={[styles.chip, { backgroundColor: courseId === null ? '#3c87f7' : theme.backgroundElement }]}>
                <ThemedText type="small" style={courseId === null ? styles.chipActive : undefined}>Unsorted</ThemedText>
              </Pressable>
              {courses.map((c) => (
                <Pressable
                  key={c.id}
                  onPress={() => setCourseId(c.id)}
                  style={[styles.chip, { backgroundColor: courseId === c.id ? '#3c87f7' : theme.backgroundElement }]}>
                  <ThemedText type="small" style={courseId === c.id ? styles.chipActive : undefined}>{c.name}</ThemedText>
                </Pressable>
              ))}
            </View>
            <View style={styles.row}>
              <TextInput
                value={newCourse}
                onChangeText={setNewCourse}
                placeholder="+ New course name"
                placeholderTextColor={theme.textSecondary}
                style={[inputStyle, styles.flex]}
              />
              <Pressable onPress={() => void addCourse()} style={[styles.addBtn, { opacity: newCourse.trim() ? 1 : 0.5 }]}>
                <ThemedText type="small" style={styles.chipActive}>Add</ThemedText>
              </Pressable>
            </View>

            <ThemedText type="small" themeColor="textSecondary">Lecture date</ThemedText>
            <TextInput
              value={dateStr}
              onChangeText={setDateStr}
              placeholder="YYYY-MM-DD"
              placeholderTextColor={theme.textSecondary}
              autoCapitalize="none"
              style={inputStyle}
            />

            <ThemedText type="small" themeColor="textSecondary">Language (blank = auto-detect)</ThemedText>
            <TextInput
              value={language}
              onChangeText={setLanguage}
              placeholder="e.g. en, de"
              placeholderTextColor={theme.textSecondary}
              autoCapitalize="none"
              style={inputStyle}
            />

            <View style={styles.actions}>
              <Pressable onPress={onCancel} style={[styles.btn, { backgroundColor: theme.backgroundElement }]}>
                <ThemedText>Cancel</ThemedText>
              </Pressable>
              <Pressable
                onPress={() =>
                  onStart({
                    title: title.trim() || defaultTitle,
                    courseId,
                    lectureDate: parseYmd(dateStr),
                    language: language.trim() || undefined,
                  })
                }
                style={[styles.btn, { backgroundColor: '#3c87f7' }]}>
                <ThemedText style={styles.startText}>Start</ThemedText>
              </Pressable>
            </View>
          </ScrollView>
        </ThemedView>
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  backdrop: { flex: 1, justifyContent: 'flex-end', backgroundColor: '#00000066' },
  sheet: { maxHeight: '88%', borderTopLeftRadius: Spacing.four, borderTopRightRadius: Spacing.four },
  content: { padding: Spacing.four, gap: Spacing.two, maxWidth: 800, width: '100%', alignSelf: 'center' },
  input: { borderRadius: Spacing.two, paddingHorizontal: Spacing.three, paddingVertical: Spacing.two, fontSize: 15 },
  chips: { flexDirection: 'row', flexWrap: 'wrap', gap: Spacing.two },
  chip: { paddingHorizontal: Spacing.three, paddingVertical: Spacing.one, borderRadius: 999 },
  chipActive: { color: '#fff', fontWeight: '700' },
  row: { flexDirection: 'row', gap: Spacing.two, alignItems: 'center' },
  flex: { flex: 1 },
  addBtn: { backgroundColor: '#3c87f7', paddingHorizontal: Spacing.three, paddingVertical: Spacing.two, borderRadius: Spacing.two },
  actions: { flexDirection: 'row', gap: Spacing.two, marginTop: Spacing.three },
  btn: { flex: 1, paddingVertical: Spacing.three, borderRadius: Spacing.three, alignItems: 'center' },
  startText: { color: '#fff', fontWeight: '700' },
});
