import React, { useState, useEffect, useRef, useMemo } from 'react';
import {
  View, Text, StyleSheet, ScrollView,
  KeyboardAvoidingView, Platform, Animated, Pressable,
} from 'react-native';
import { showAlert } from '../components/NovaAlert';
import ScreenWrapper from '../components/ScreenWrapper';
import Input from '../components/Input';
import HabitInput from '../components/HabitInput';
import Button from '../components/Button';
import useIdentityStore from '../store/useIdentityStore';
import useAppStore from '../store/useAppStore';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';
import { getSuggestionsForIdentity } from '../utils/helpers';

const MAX_HABITS = 5;

export default function CreateIdentityScreen({ navigation }) {
  const initialIdentity = useAppStore((s) => s.initialIdentity);
  const createIdentity = useIdentityStore((s) => s.createIdentity);

  const [title, setTitle] = useState(initialIdentity || '');
  const [habits, setHabits] = useState([{ id: 1, value: '' }]);
  const [loading, setLoading] = useState(false);
  const [lastAddedId, setLastAddedId] = useState(null);
  const nextId = useRef(2);

  // Entrance animation
  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: 500, useNativeDriver: true }),
      Animated.timing(slideAnim, { toValue: 0, duration: 500, useNativeDriver: true }),
    ]).start();
  }, []);

  // Smart suggestions based on identity input
  const suggestions = useMemo(() => {
    const existing = habits.map((h) => h.value.toLowerCase().trim()).filter(Boolean);
    return getSuggestionsForIdentity(title).filter(
      (s) => !existing.some((e) => e === s.toLowerCase())
    );
  }, [title, habits]);

  // --- Habit CRUD ---
  const addHabit = (prefill = '') => {
    if (habits.length >= MAX_HABITS) return;
    const id = nextId.current++;
    setHabits((prev) => [...prev, { id, value: prefill }]);
    setLastAddedId(id);
  };

  const updateHabit = (id, value) => {
    setHabits((prev) => prev.map((h) => (h.id === id ? { ...h, value } : h)));
  };

  const deleteHabit = (id) => {
    if (habits.length <= 1) return; // keep at least 1
    setHabits((prev) => prev.filter((h) => h.id !== id));
  };

  const addSuggestion = (text) => {
    // Fill first empty habit, or add new one
    const emptyHabit = habits.find((h) => !h.value.trim());
    if (emptyHabit) {
      updateHabit(emptyHabit.id, text);
    } else {
      addHabit(text);
    }
  };

  // --- Submit ---
  const handleCreate = async () => {
    const trimmedTitle = title.trim();
    if (!trimmedTitle) {
      showAlert('One thing missing', 'Tell us who you want to become.');
      return;
    }

    const validHabits = habits
      .map((h) => h.value.trim())
      .filter(Boolean);

    if (validHabits.length === 0) {
      showAlert('No habits yet', 'Add at least one habit to start.');
      return;
    }

    // Check for duplicates
    const unique = [...new Set(validHabits.map((h) => h.toLowerCase()))];
    if (unique.length < validHabits.length) {
      showAlert('Already added', 'Looks like you have a duplicate. Remove it and try again.');
      return;
    }

    setLoading(true);
    try {
      const customHabits = validHabits.map((h) => ({ title: h }));
      await createIdentity(trimmedTitle, '', customHabits, '');
      navigation.reset({ index: 0, routes: [{ name: 'MainTabs' }] });
    } catch (error) {
      showAlert('Error', error.message);
    } finally {
      setLoading(false);
    }
  };

  const validCount = habits.filter((h) => h.value.trim()).length;

  return (
    <ScreenWrapper>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        style={styles.flex}
      >
        <Animated.View style={[styles.flex, { opacity: fadeAnim, transform: [{ translateY: slideAnim }] }]}>
          <ScrollView
            style={styles.scroll}
            contentContainerStyle={styles.scrollContent}
            showsVerticalScrollIndicator={false}
            keyboardShouldPersistTaps="handled"
          >
            {/* Header */}
            <Text style={styles.title}>Who do you want to be?</Text>
            <Text style={styles.subtitle}>Describe the person you're becoming, then add the habits that'll get you there.</Text>

            {/* Identity Input */}
            <Input
              label="Your identity"
              value={title}
              onChangeText={setTitle}
              placeholder="e.g., Someone who shows up every day"
            />

            {/* Habit Section */}
            <View style={styles.habitSection}>
              <View style={styles.habitHeader}>
                <Text style={styles.sectionTitle}>Your daily habits</Text>
                <Text style={styles.habitCounter}>{validCount} / {MAX_HABITS}</Text>
              </View>

              {/* Habit Inputs */}
              {habits.map((habit, idx) => (
                <HabitInput
                  key={habit.id}
                  index={idx}
                  value={habit.value}
                  onChangeText={(text) => updateHabit(habit.id, text)}
                  onDelete={() => deleteHabit(habit.id)}
                  autoFocus={habit.id === lastAddedId}
                />
              ))}

              {/* Add Habit Button */}
              {habits.length < MAX_HABITS && (
                <Pressable
                  style={({ pressed }) => [styles.addBtn, pressed && styles.addBtnPressed]}
                  onPress={() => addHabit()}
                >
                  <Text style={styles.addBtnIcon}>+</Text>
                  <Text style={styles.addBtnText}>Add another</Text>
                </Pressable>
              )}
            </View>

            {/* Smart Suggestions */}
            {suggestions.length > 0 && (
              <View style={styles.suggestionsSection}>
                <Text style={styles.suggestionsTitle}>Ideas for you</Text>
                <View style={styles.suggestionsGrid}>
                  {suggestions.map((s) => (
                    <Pressable
                      key={s}
                      style={({ pressed }) => [styles.suggestionChip, pressed && styles.suggestionChipPressed]}
                      onPress={() => addSuggestion(s)}
                      disabled={habits.length >= MAX_HABITS && !habits.some((h) => !h.value.trim())}
                    >
                      <Text style={styles.suggestionPlus}>+</Text>
                      <Text style={styles.suggestionText}>{s}</Text>
                    </Pressable>
                  ))}
                </View>
              </View>
            )}

            {/* Submit */}
            <View style={styles.submitArea}>
              <Button
                title="Begin My Journey"
                onPress={handleCreate}
                loading={loading}
                disabled={!title.trim() || validCount === 0}
                style={styles.submitBtn}
              />
              <Text style={styles.submitHint}>
                {validCount === 0
                  ? 'Add at least one habit to get started'
                  : `${validCount} habit${validCount > 1 ? 's' : ''} ready. Let's go.`}
              </Text>
            </View>
          </ScrollView>
        </Animated.View>
      </KeyboardAvoidingView>
    </ScreenWrapper>
  );
}

const styles = StyleSheet.create({
  flex: { flex: 1 },
  scroll: { flex: 1 },
  scrollContent: {
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.xxl,
    paddingBottom: spacing.xxl,
  },

  // Header
  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.xl,
  },

  // Habits
  habitSection: {
    marginTop: spacing.md,
  },
  habitHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: spacing.md,
  },
  sectionTitle: {
    color: colors.text,
    fontSize: fonts.sizes.lg,
    fontWeight: fonts.weights.semibold,
  },
  habitCounter: {
    color: colors.textMuted,
    fontSize: fonts.sizes.sm,
    fontWeight: fonts.weights.medium,
  },

  // Add button
  addBtn: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: spacing.md,
    borderRadius: borderRadius.md,
    borderWidth: 1.5,
    borderColor: colors.border,
    borderStyle: 'dashed',
    marginTop: spacing.xs,
  },
  addBtnPressed: { opacity: 0.6 },
  addBtnIcon: {
    color: colors.primary,
    fontSize: fonts.sizes.lg,
    fontWeight: fonts.weights.bold,
    marginRight: spacing.sm,
  },
  addBtnText: {
    color: colors.primary,
    fontSize: fonts.sizes.md,
    fontWeight: fonts.weights.medium,
  },

  // Suggestions
  suggestionsSection: {
    marginTop: spacing.xl,
  },
  suggestionsTitle: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.sm,
    fontWeight: fonts.weights.medium,
    marginBottom: spacing.sm,
  },
  suggestionsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: spacing.sm,
  },
  suggestionChip: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.surface,
    borderRadius: borderRadius.full,
    paddingVertical: spacing.sm,
    paddingHorizontal: spacing.md,
    borderWidth: 1,
    borderColor: colors.border,
  },
  suggestionChipPressed: { opacity: 0.6, borderColor: colors.primary },
  suggestionPlus: {
    color: colors.accent,
    fontSize: fonts.sizes.sm,
    fontWeight: fonts.weights.bold,
    marginRight: spacing.xs,
  },
  suggestionText: {
    color: colors.text,
    fontSize: fonts.sizes.sm,
  },

  // Submit
  submitArea: {
    marginTop: spacing.xxl,
    alignItems: 'center',
  },
  submitBtn: {
    width: '100%',
  },
  submitHint: {
    color: colors.textMuted,
    fontSize: fonts.sizes.sm,
    marginTop: spacing.md,
    textAlign: 'center',
  },
});
