import React, { useState, useRef, useEffect } from 'react';
import {
  View, Text, TextInput, StyleSheet,
  KeyboardAvoidingView, Platform, Animated, ScrollView,
} from 'react-native';
import { showAlert } from '../components/NovaAlert';
import ScreenWrapper from '../components/ScreenWrapper';
import Button from '../components/Button';
import { generateFromStory } from '../services/aiService';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';

const MIN_CHARS = 30;
const MAX_CHARS = 1000;

const PROMPTS = [
  '"I want to stop procrastinating and start showing up for myself every day..."',
  '"I used to be fit and confident, but I lost myself. I want that person back..."',
  '"I dream of being someone who reads, learns, and never stops growing..."',
  '"I\'m tired of being anxious. I want to be calm, focused, and in control..."',
];

export default function IdentityStoryScreen({ navigation }) {
  const [story, setStory] = useState('');
  const [loading, setLoading] = useState(false);
  const [promptIndex] = useState(() => Math.floor(Math.random() * PROMPTS.length));

  const fadeAnim = useRef(new Animated.Value(0)).current;
  const slideAnim = useRef(new Animated.Value(20)).current;

  useEffect(() => {
    Animated.parallel([
      Animated.timing(fadeAnim, { toValue: 1, duration: 600, useNativeDriver: true }),
      Animated.timing(slideAnim, { toValue: 0, duration: 600, useNativeDriver: true }),
    ]).start();
  }, []);

  const handleGenerate = async () => {
    const trimmed = story.trim();
    if (trimmed.length < MIN_CHARS) {
      showAlert('Just a bit more', 'Write a few more sentences — it helps us understand you better.');
      return;
    }

    setLoading(true);
    try {
      const result = await generateFromStory(trimmed);
      if (result.source === 'fallback') {
        showAlert(
          'We went a different route',
          "AI wasn't available, but we still created something for you. You can change anything on the next screen.",
          [{ text: 'Continue', onPress: () => navigation.navigate('HabitSelection', { aiResult: result, story: trimmed }) }]
        );
      } else {
        navigation.navigate('HabitSelection', { aiResult: result, story: trimmed });
      }
    } catch (e) {
      showAlert('Error', e.message || 'Something went wrong. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleSkip = () => {
    navigation.navigate('CreateIdentity');
  };

  const charCount = story.trim().length;
  const isValid = charCount >= MIN_CHARS;

  return (
    <ScreenWrapper>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        style={styles.flex}
      >
        <ScrollView
          style={styles.flex}
          contentContainerStyle={styles.scrollContent}
          keyboardShouldPersistTaps="handled"
          showsVerticalScrollIndicator={false}
        >
          <Animated.View style={{ opacity: fadeAnim, transform: [{ translateY: slideAnim }] }}>
            {/* Header */}
            <Text style={styles.title}>Tell us about you</Text>
            <Text style={styles.subtitle}>
              Who are you right now? And who do you want to become? Write it down — this is just for you.
            </Text>

            {/* AI badge */}
            <View style={styles.aiBadge}>
              <Text style={styles.aiBadgeIcon}>✦</Text>
              <Text style={styles.aiBadgeText}>We'll turn your story into a personal plan</Text>
            </View>

            {/* Story input */}
            <View style={styles.inputContainer}>
              <TextInput
                style={styles.storyInput}
                value={story}
                onChangeText={(t) => setStory(t.slice(0, MAX_CHARS))}
                placeholder={PROMPTS[promptIndex]}
                placeholderTextColor={colors.textMuted}
                multiline
                textAlignVertical="top"
                selectionColor={colors.primary}
              />
              <Text style={[styles.charCount, isValid && styles.charCountValid]}>
                {charCount} / {MIN_CHARS}+
              </Text>
            </View>

            {/* Tips */}
            <View style={styles.tipsCard}>
              <Text style={styles.tipsTitle}>Not sure what to write?</Text>
              <Text style={styles.tipItem}>• What feels hard in your life right now?</Text>
              <Text style={styles.tipItem}>• Who do you wish you could be?</Text>
              <Text style={styles.tipItem}>• What would be different if you made the change?</Text>
            </View>

            {/* Actions */}
            <Button
              title={loading ? 'Reading your story...' : 'Show Me My Path'}
              onPress={handleGenerate}
              loading={loading}
              disabled={!isValid}
              style={styles.generateBtn}
            />

            <Button
              title="I'll set it up myself"
              onPress={handleSkip}
              variant="secondary"
              disabled={loading}
              style={styles.skipBtn}
            />
          </Animated.View>
        </ScrollView>
      </KeyboardAvoidingView>
    </ScreenWrapper>
  );
}

const styles = StyleSheet.create({
  flex: { flex: 1 },
  scrollContent: {
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.xxl,
    paddingBottom: spacing.xxl,
  },
  title: {
    color: colors.text,
    fontSize: fonts.sizes.xxl,
    fontWeight: fonts.weights.bold,
    marginBottom: spacing.xs,
  },
  subtitle: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
    lineHeight: 22,
    marginBottom: spacing.lg,
  },
  aiBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(108, 99, 255, 0.08)',
    borderRadius: borderRadius.full,
    paddingVertical: spacing.sm,
    paddingHorizontal: spacing.md,
    alignSelf: 'flex-start',
    marginBottom: spacing.lg,
    borderWidth: 1,
    borderColor: 'rgba(108, 99, 255, 0.2)',
  },
  aiBadgeIcon: {
    color: colors.primary,
    fontSize: 14,
    marginRight: spacing.sm,
  },
  aiBadgeText: {
    color: colors.primaryLight,
    fontSize: fonts.sizes.xs,
    fontWeight: fonts.weights.medium,
  },
  inputContainer: {
    marginBottom: spacing.lg,
  },
  storyInput: {
    backgroundColor: colors.surface,
    borderRadius: borderRadius.md,
    borderWidth: 1,
    borderColor: colors.border,
    paddingHorizontal: spacing.md,
    paddingTop: spacing.md,
    paddingBottom: spacing.xl,
    color: colors.text,
    fontSize: fonts.sizes.md,
    minHeight: 160,
    lineHeight: 24,
  },
  charCount: {
    position: 'absolute',
    bottom: spacing.sm,
    right: spacing.md,
    color: colors.textMuted,
    fontSize: fonts.sizes.xs,
  },
  charCountValid: {
    color: colors.success,
  },
  tipsCard: {
    backgroundColor: colors.surface,
    borderRadius: borderRadius.md,
    padding: spacing.md,
    borderWidth: 1,
    borderColor: colors.border,
    marginBottom: spacing.xl,
  },
  tipsTitle: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.sm,
    fontWeight: fonts.weights.semibold,
    marginBottom: spacing.sm,
  },
  tipItem: {
    color: colors.textMuted,
    fontSize: fonts.sizes.sm,
    lineHeight: 22,
  },
  generateBtn: {
    marginBottom: spacing.sm,
  },
  skipBtn: {},
});
