import { useState } from 'react';
import {
  View, Text, TextInput, TouchableOpacity, StyleSheet,
  ScrollView, ActivityIndicator, KeyboardAvoidingView, Platform,
} from 'react-native';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/api/client';
import { adaptParseResponse } from '@/api/parseAdapter';
import { getCachedParse, cacheParse } from '@/db/local';
import { Colors, Spacing, Typography, Radius } from '@/theme';
import ParadigmSheet from '@/screens/ParadigmSheet';
import type { ParseResult } from '@/types';

export default function AnalyzeScreen() {
  const [input, setInput] = useState('');
  const [submitted, setSubmitted] = useState('');

  const { data, isLoading, isError, error } = useQuery<ParseResult[]>({
    queryKey: ['parse', submitted],
    queryFn: async () => {
      try {
        const raw = await api.get(`/api/parse?q=${encodeURIComponent(submitted)}`);
        await cacheParse(submitted, raw);
        return adaptParseResponse(raw);
      } catch (err) {
        const cached = await getCachedParse(submitted);
        if (cached) return adaptParseResponse(cached);
        throw err;
      }
    },
    enabled: !!submitted,
    staleTime: Infinity,
    retry: false,
  });

  function submit() {
    const trimmed = input.trim();
    if (trimmed) setSubmitted(trimmed);
  }

  return (
    <KeyboardAvoidingView
      style={{ flex: 1 }}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <ScrollView
        style={styles.container}
        contentContainerStyle={styles.content}
        keyboardShouldPersistTaps="handled"
      >
        {/* Search bar */}
        <View style={styles.searchRow}>
          <TextInput
            style={styles.input}
            placeholder="Enter a Latin or Greek word…"
            placeholderTextColor={Colors.textMuted}
            value={input}
            onChangeText={setInput}
            onSubmitEditing={submit}
            autoCorrect={false}
            autoCapitalize="none"
            returnKeyType="search"
          />
          <TouchableOpacity style={styles.searchButton} onPress={submit}>
            <Text style={styles.searchButtonText}>Parse</Text>
          </TouchableOpacity>
        </View>

        {isLoading && (
          <View style={styles.centered}>
            <ActivityIndicator color={Colors.primary} />
          </View>
        )}

        {isError && (
          <Text style={styles.errorText}>
            {(error as Error)?.message ?? 'Could not parse — check your connection or try again.'}
          </Text>
        )}

        {data?.map((result: ParseResult, i: number) => (
          <ParseResultCard key={i} result={result} />
        ))}

        {data && data.length === 0 && (
          <Text style={styles.emptyText}>No results found for "{submitted}"</Text>
        )}
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

function ParseResultCard({ result }: { result: ParseResult }) {
  const [showParadigm, setShowParadigm] = useState(false);

  return (
    <View style={styles.resultCard}>
      <View style={styles.resultHeader}>
        <View>
          <Text style={styles.headword}>{result.lemma}</Text>
          <Text style={styles.pos}>{result.partOfSpeech}</Text>
        </View>
        {result.shortDef && (
          <Text style={styles.shortDef}>{result.shortDef}</Text>
        )}
      </View>

      <Text style={styles.morphology}>{result.morphology}</Text>

      <View style={styles.actionRow}>
        {result.language && (
          <TouchableOpacity style={styles.actionBtn} onPress={() => setShowParadigm(true)}>
            <Text style={styles.actionBtnText}>Paradigm</Text>
          </TouchableOpacity>
        )}
      </View>

      {result.source && (
        <Text style={styles.source}>via {result.source}</Text>
      )}

      {showParadigm && result.language && (
        <ParadigmSheet
          lemma={result.lemma}
          language={result.language}
          fullDef={result.fullDef}
          onClose={() => setShowParadigm(false)}
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: Colors.background },
  content: { padding: Spacing.lg, gap: Spacing.md },
  searchRow: { flexDirection: 'row', gap: Spacing.sm },
  input: {
    flex: 1,
    backgroundColor: Colors.surface,
    borderWidth: 1,
    borderColor: Colors.border,
    borderRadius: Radius.md,
    paddingHorizontal: Spacing.md,
    paddingVertical: Spacing.md,
    fontSize: Typography.size.base,
    color: Colors.text,
  },
  searchButton: {
    backgroundColor: Colors.primary,
    borderRadius: Radius.md,
    paddingHorizontal: Spacing.lg,
    justifyContent: 'center',
  },
  searchButtonText: { color: '#fff', fontWeight: Typography.weight.semibold },
  centered: { paddingVertical: Spacing['2xl'], alignItems: 'center' },
  errorText: { color: Colors.error, fontSize: Typography.size.sm, textAlign: 'center' },
  emptyText: { color: Colors.textMuted, fontSize: Typography.size.sm, textAlign: 'center' },
  resultCard: {
    backgroundColor: Colors.surface,
    borderRadius: Radius.lg,
    borderWidth: 1,
    borderColor: Colors.border,
    padding: Spacing.lg,
    gap: Spacing.sm,
  },
  resultHeader: { gap: Spacing.sm },
  headword: {
    fontSize: Typography.size.xl,
    fontWeight: Typography.weight.bold,
    color: Colors.primary,
  },
  pos: {
    fontSize: Typography.size.xs,
    color: Colors.textMuted,
    textTransform: 'uppercase',
    letterSpacing: 0.8,
  },
  shortDef: { fontSize: Typography.size.base, color: Colors.text, lineHeight: 22 },
  morphology: {
    fontSize: Typography.size.sm,
    color: Colors.textMuted,
    backgroundColor: Colors.background,
    borderRadius: Radius.sm,
    padding: Spacing.sm,
    fontFamily: Platform.OS === 'ios' ? 'Menlo' : 'monospace',
  },
  actionRow: { flexDirection: 'row', gap: Spacing.sm, marginTop: Spacing.xs },
  actionBtn: {
    backgroundColor: Colors.primary + '18',
    borderRadius: Radius.sm,
    paddingHorizontal: Spacing.sm,
    paddingVertical: 4,
  },
  actionBtnText: {
    fontSize: Typography.size.xs,
    color: Colors.primary,
    fontWeight: Typography.weight.semibold,
  },
  source: { fontSize: Typography.size.xs, color: Colors.textMuted, textAlign: 'right' },
});

