import React, { useState, useRef, useEffect } from 'react';
import {
  View, Text, StyleSheet, Pressable,
  TextInput, Animated,
} from 'react-native';
import { showAlert } from '../components/NovaAlert';
import ScreenWrapper from '../components/ScreenWrapper';
import Button from '../components/Button';
import useIdentityStore from '../store/useIdentityStore';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';

const MAX_HABITS = 5;

function HabitChip({ text, selected, onToggle, disabled }) {
  return (
    <Pressable
      style={[styles.chip, selected && styles.chipSelected, disabled && !selected && styles.chipDisabled]}
      onPress={onToggle}
      disabled={disabled && !selected}
    >
      <Text style={[styles.chipCheck, selected && styles.chipCheckSelected]}>
        {selected ? '✓' : '+'}
      </Text>
      <Text style={[styles.chipText, selected && styles.chipTextSelected]}>{text}</Text>
    </Pressable>
  );
}

export default function HabitSelectionScreen({ navigation, route }) {
  const { aiResult, story } = route.params;
  const createIdentity = useIdentityStore((s) => s.createIdentity);

  const [selectedHabits, setSelectedHabits] = useState([]);
  const [customHabit, setCustomHabit] = useState('');
  const [customHabits, setCustomHabits] = useState([]);
  const [editingTitle, setEditingTitle] = useState(false);
  const [title, setTitle] = useState(aiResult.identity_title);
  const [loading, setLoading] = useState(false);

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

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

  const allSelected = [...selectedHabits, ...customHabits];
  const atMax = allSelected.length >= MAX_HABITS;

  const toggleHabit = (habit) => {
    setSelectedHabits((prev) =>
      prev.includes(habit)
        ? prev.filter((h) => h !== habit)
        : atMax ? prev : [...prev, habit]
    );
  };

  const addCustomHabit = () => {
    const trimmed = customHabit.trim();
    if (!trimmed) return;
    if (allSelected.length >= MAX_HABITS) {
      showAlert('Limit', `Maximum ${MAX_HABITS} habits allowed.`);
      return;
    }
    if ([...selectedHabits, ...customHabits].some((h) => h.toLowerCase() === trimmed.toLowerCase())) {
      showAlert('Duplicate', 'This habit is already in your list.');
      return;
    }
    setCustomHabits((prev) => [...prev, trimmed]);
    setCustomHabit('');
  };

  const removeCustom = (habit) => {
    setCustomHabits((prev) => prev.filter((h) => h !== habit));
  };

  const handleStart = async () => {
    if (allSelected.length === 0) {
      showAlert('No Habits', 'Please select at least 1 habit.');
      return;
    }

    setLoading(true);
    try {
      const habits = allSelected.map((h) => ({ title: h }));
      const identityTitle = title.trim() || aiResult.identity_title;
      const description = aiResult.identity_summary || '';
      await createIdentity(identityTitle, description, habits, story || '');
      navigation.reset({ index: 0, routes: [{ name: 'MainTabs' }] });
    } catch (e) {
      showAlert('Error', e.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <ScreenWrapper>
      <Animated.ScrollView
        style={[styles.scroll, { opacity: fadeAnim }]}
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps="handled"
      >
        {/* Source badge */}
        <View style={styles.sourceBadge}>
          <Text style={styles.sourceBadgeText}>
            {aiResult.source === 'ai' ? '✦ AI Generated' : '⚡ Smart Suggestions'}
          </Text>
        </View>

        {/* Identity Title */}
        <View style={styles.identityCard}>
          <Text style={styles.identityLabel}>YOUR NEW IDENTITY</Text>
          {editingTitle ? (
            <TextInput
              style={styles.titleInput}
              value={title}
              onChangeText={setTitle}
              onBlur={() => setEditingTitle(false)}
              autoFocus
              selectionColor={colors.primary}
            />
          ) : (
            <Pressable onPress={() => setEditingTitle(true)}>
              <Text style={styles.identityTitle}>{title}</Text>
              <Text style={styles.editHint}>Tap to edit</Text>
            </Pressable>
          )}
        </View>

        {/* Summary */}
        <Text style={styles.summary}>{aiResult.identity_summary}</Text>

        {/* Habit selection */}
        <View style={styles.habitSection}>
          <View style={styles.habitHeader}>
            <Text style={styles.sectionTitle}>Select Your Habits</Text>
            <Text style={[styles.counter, atMax && styles.counterFull]}>
              {allSelected.length} / {MAX_HABITS}
            </Text>
          </View>

          {/* AI suggested habits */}
          {aiResult.suggested_habits.map((habit) => (
            <HabitChip
              key={habit}
              text={habit}
              selected={selectedHabits.includes(habit)}
              onToggle={() => toggleHabit(habit)}
              disabled={atMax}
            />
          ))}

          {/* Custom habits */}
          {customHabits.map((habit) => (
            <View key={habit} style={styles.customChipRow}>
              <View style={[styles.chip, styles.chipSelected, styles.customChip]}>
                <Text style={[styles.chipCheck, styles.chipCheckSelected]}>✓</Text>
                <Text style={[styles.chipText, styles.chipTextSelected, { flex: 1 }]}>{habit}</Text>
              </View>
              <Pressable onPress={() => removeCustom(habit)} style={styles.removeBtn}>
                <Text style={styles.removeBtnText}>✕</Text>
              </Pressable>
            </View>
          ))}

          {/* Add custom */}
          {!atMax && (
            <View style={styles.addRow}>
              <TextInput
                style={styles.addInput}
                value={customHabit}
                onChangeText={setCustomHabit}
                placeholder="Add your own habit..."
                placeholderTextColor={colors.textMuted}
                selectionColor={colors.primary}
                onSubmitEditing={addCustomHabit}
                returnKeyType="done"
              />
              <Pressable
                style={[styles.addBtn, !customHabit.trim() && styles.addBtnDisabled]}
                onPress={addCustomHabit}
                disabled={!customHabit.trim()}
              >
                <Text style={styles.addBtnText}>+</Text>
              </Pressable>
            </View>
          )}
        </View>

        {/* Start button */}
        <Button
          title="Start 40-Day Journey"
          onPress={handleStart}
          loading={loading}
          disabled={allSelected.length === 0}
          style={styles.startBtn}
        />

        <Text style={styles.startHint}>
          {allSelected.length === 0
            ? 'Select at least 1 habit to begin'
            : `${allSelected.length} habit${allSelected.length > 1 ? 's' : ''} selected. Ready to transform.`}
        </Text>
      </Animated.ScrollView>
    </ScreenWrapper>
  );
}

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

  // Source badge
  sourceBadge: {
    alignSelf: 'flex-start',
    backgroundColor: 'rgba(108, 99, 255, 0.08)',
    borderRadius: borderRadius.full,
    paddingVertical: spacing.xs,
    paddingHorizontal: spacing.md,
    borderWidth: 1,
    borderColor: 'rgba(108, 99, 255, 0.2)',
    marginBottom: spacing.lg,
  },
  sourceBadgeText: {
    color: colors.primaryLight,
    fontSize: fonts.sizes.xs,
    fontWeight: fonts.weights.medium,
  },

  // Identity card
  identityCard: {
    backgroundColor: colors.surface,
    borderRadius: borderRadius.lg,
    padding: spacing.lg,
    borderWidth: 1,
    borderColor: colors.primary,
    marginBottom: spacing.md,
  },
  identityLabel: {
    color: colors.primary,
    fontSize: fonts.sizes.xs,
    fontWeight: fonts.weights.bold,
    letterSpacing: 2,
    marginBottom: spacing.sm,
  },
  identityTitle: {
    color: colors.text,
    fontSize: fonts.sizes.xl,
    fontWeight: fonts.weights.bold,
    lineHeight: 32,
  },
  titleInput: {
    color: colors.text,
    fontSize: fonts.sizes.xl,
    fontWeight: fonts.weights.bold,
    borderBottomWidth: 1,
    borderBottomColor: colors.primary,
    paddingVertical: spacing.xs,
  },
  editHint: {
    color: colors.textMuted,
    fontSize: fonts.sizes.xs,
    marginTop: spacing.xs,
  },

  // Summary
  summary: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
    lineHeight: 24,
    marginBottom: spacing.xl,
  },

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

  // Chips
  chip: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.surface,
    borderRadius: borderRadius.md,
    paddingVertical: spacing.md,
    paddingHorizontal: spacing.md,
    borderWidth: 1,
    borderColor: colors.border,
    marginBottom: spacing.sm,
  },
  chipSelected: {
    borderColor: colors.primary,
    backgroundColor: 'rgba(108, 99, 255, 0.08)',
  },
  chipDisabled: {
    opacity: 0.4,
  },
  chipCheck: {
    width: 24,
    height: 24,
    borderRadius: 12,
    borderWidth: 1.5,
    borderColor: colors.textMuted,
    textAlign: 'center',
    lineHeight: 22,
    fontSize: 12,
    color: colors.textMuted,
    marginRight: spacing.md,
    flexShrink: 0,
  },
  chipCheckSelected: {
    borderColor: colors.primary,
    backgroundColor: colors.primary,
    color: colors.text,
  },
  chipText: {
    color: colors.text,
    fontSize: fonts.sizes.md,
    flex: 1,
    flexWrap: 'wrap',
  },
  chipTextSelected: {
    color: colors.text,
    fontWeight: fonts.weights.medium,
  },

  // Custom chips
  customChipRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: spacing.sm,
  },
  customChip: {
    flex: 1,
    marginBottom: 0,
  },
  removeBtn: {
    width: 36,
    height: 36,
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: spacing.sm,
  },
  removeBtnText: {
    color: colors.error,
    fontSize: 16,
  },

  // Add custom
  addRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: spacing.xs,
  },
  addInput: {
    flex: 1,
    backgroundColor: colors.surface,
    borderRadius: borderRadius.md,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.md,
    color: colors.text,
    fontSize: fonts.sizes.md,
    borderWidth: 1,
    borderColor: colors.border,
    borderStyle: 'dashed',
  },
  addBtn: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: spacing.sm,
  },
  addBtnDisabled: {
    opacity: 0.4,
  },
  addBtnText: {
    color: colors.text,
    fontSize: 22,
    fontWeight: fonts.weights.bold,
    lineHeight: 24,
  },

  // Start
  startBtn: {},
  startHint: {
    color: colors.textMuted,
    fontSize: fonts.sizes.sm,
    textAlign: 'center',
    marginTop: spacing.md,
  },
});
