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 CAT_ICONS = { Mind: '🧠', Body: '💪', Emotion: '❤️', Social: '👥', Skill: '⚡', Discipline: '🎯', Health: '🌿', Creative: '🎨' };

function formatDuration(min) {
  if (!min || min <= 0) return null;
  if (min >= 60) return `${Math.floor(min / 60)}h${min % 60 > 0 ? ` ${min % 60}m` : ''}`;
  return `${min} min`;
}

function HabitChip({ habit, selected, onToggle, isPriority }) {
  const dur = formatDuration(habit.duration);
  const hasTime = habit.best_time && habit.best_time.length >= 4 && habit.best_time !== '--';
  const hasMeta = hasTime || dur;
  return (
    <Pressable
      style={[styles.chip, selected && styles.chipSelected]}
      onPress={onToggle}
    >
      {/* Checkbox */}
      <View style={styles.chipLeft}>
        <Text style={[styles.chipCheck, selected && styles.chipCheckSelected]}>
          {selected ? '\u2713' : '+'}
        </Text>
        {isPriority && selected && (
          <View style={styles.priorityBadge}>
            <Text style={styles.priorityBadgeText}>{'\u2605'}</Text>
          </View>
        )}
      </View>

      {/* Content */}
      <View style={styles.chipBody}>
        {/* Title */}
        <Text style={[styles.chipText, selected && styles.chipTextSelected]}>{habit.title}</Text>

        {/* Description / Why */}
        {habit.why ? <Text style={styles.chipWhy}>{habit.why}</Text> : null}

        {/* ---- Separator ---- */}
        {hasMeta && <View style={styles.chipSeparator} />}

        {/* Time & Duration */}
        {hasMeta && (
          <View style={styles.chipTimeRow}>
            {hasTime && (
              <View style={styles.chipTimeItem}>
                <Text style={styles.chipTimeIcon}>{'\u{1F554}'}</Text>
                <Text style={styles.chipTimeLabel}>{habit.best_time}</Text>
              </View>
            )}
            {dur && (
              <View style={styles.chipTimeItem}>
                <Text style={styles.chipTimeIcon}>{'\u23F1'}</Text>
                <Text style={styles.chipTimeLabel}>{dur}</Text>
              </View>
            )}
          </View>
        )}
      </View>

      {/* Category icon */}
      {habit.category && (
        <Text style={styles.catBadge}>{CAT_ICONS[habit.category] || ''}</Text>
      )}
    </Pressable>
  );
}

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

  const priorityHabits = aiResult.priority_habits || [];
  const additionalHabits = aiResult.suggested_habits || [];

  // Pre-select the 5 priority habit titles
  const [selectedTitles, setSelectedTitles] = useState(
    () => priorityHabits.map((h) => h.title)
  );
  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 allSelectedCount = selectedTitles.length + customHabits.length;
  const allHabitsMap = [...priorityHabits, ...additionalHabits];

  const toggleHabit = (habitTitle) => {
    setSelectedTitles((prev) =>
      prev.includes(habitTitle)
        ? prev.filter((t) => t !== habitTitle)
        : [...prev, habitTitle]
    );
  };

  const addCustomHabit = () => {
    const trimmed = customHabit.trim();
    if (!trimmed) return;
    const allTitles = [...selectedTitles, ...customHabits];
    if (allTitles.some((t) => t.toLowerCase() === trimmed.toLowerCase())) {
      showAlert('Already added', "You've already got that one.");
      return;
    }
    setCustomHabits((prev) => [...prev, trimmed]);
    setCustomHabit('');
  };

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

  const handleStart = async () => {
    if (allSelectedCount === 0) {
      showAlert('No habits yet', 'Choose at least one habit to begin your journey.');
      return;
    }

    setLoading(true);
    try {
      // Build habits array — rich objects for AI habits, simple for custom
      const selectedRich = selectedTitles.map((t) => {
        const found = allHabitsMap.find((h) => h.title === t);
        return found || { title: t };
      });
      const customRich = customHabits.map((t) => ({ title: t }));
      const habits = [...selectedRich, ...customRich];

      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 change this</Text>
            </Pressable>
          )}
        </View>

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

        {/* Priority Habits (pre-selected) */}
        {priorityHabits.length > 0 && (
          <View style={styles.habitSection}>
            <View style={styles.habitHeader}>
              <Text style={styles.sectionTitle}>★ Top Priority</Text>
              <Text style={styles.counter}>{allSelectedCount} selected</Text>
            </View>
            {priorityHabits.map((habit) => (
              <HabitChip
                key={habit.title}
                habit={habit}
                selected={selectedTitles.includes(habit.title)}
                onToggle={() => toggleHabit(habit.title)}
                isPriority
              />
            ))}
          </View>
        )}

        {/* Additional Habits */}
        {additionalHabits.length > 0 && (
          <View style={styles.habitSection}>
            <Text style={styles.sectionTitle}>More Recommendations</Text>
            {additionalHabits.map((habit) => (
              <HabitChip
                key={habit.title}
                habit={habit}
                selected={selectedTitles.includes(habit.title)}
                onToggle={() => toggleHabit(habit.title)}
                isPriority={false}
              />
            ))}
          </View>
        )}

        {/* Custom habits */}
        {customHabits.length > 0 && (
          <View style={styles.habitSection}>
            <Text style={styles.sectionTitle}>Your Custom Habits</Text>
            {customHabits.map((habit) => (
              <View key={habit} style={styles.customChipRow}>
                <View style={[styles.chip, styles.chipSelected, styles.customChip]}>
                  <Text style={[styles.chipCheck, styles.chipCheckSelected]}>✓</Text>
                  <View style={styles.chipBody}>
                    <Text style={[styles.chipText, styles.chipTextSelected]}>{habit}</Text>
                  </View>
                </View>
                <Pressable onPress={() => removeCustom(habit)} style={styles.removeBtn}>
                  <Text style={styles.removeBtnText}>✕</Text>
                </Pressable>
              </View>
            ))}
          </View>
        )}

        {/* Add custom */}
        <View style={styles.addRow}>
          <TextInput
            style={styles.addInput}
            value={customHabit}
            onChangeText={setCustomHabit}
            placeholder="Or add something personal..."
            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>

        {/* Start button */}
        <Button
          title="Begin My Journey"
          onPress={handleStart}
          loading={loading}
          disabled={allSelectedCount === 0}
          style={styles.startBtn}
        />

        <Text style={styles.startHint}>
          {allSelectedCount === 0
            ? 'Pick at least one habit to get started'
            : `${allSelectedCount} habit${allSelectedCount > 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 * 2,
  },

  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,
  },

  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: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
    lineHeight: 24,
    marginBottom: spacing.xl,
  },

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

  chip: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    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)',
  },
  chipLeft: {
    alignItems: 'center',
    marginRight: spacing.md,
    paddingTop: 2,
  },
  chipCheck: {
    width: 24,
    height: 24,
    borderRadius: 12,
    borderWidth: 1.5,
    borderColor: colors.textMuted,
    textAlign: 'center',
    lineHeight: 22,
    fontSize: 12,
    color: colors.textMuted,
    flexShrink: 0,
  },
  chipCheckSelected: {
    borderColor: colors.primary,
    backgroundColor: colors.primary,
    color: colors.text,
  },
  chipBody: {
    flex: 1,
  },
  chipText: {
    color: colors.text,
    fontSize: fonts.sizes.md,
    flexWrap: 'wrap',
  },
  chipTextSelected: {
    color: colors.text,
    fontWeight: fonts.weights.semibold,
  },
  chipWhy: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.xs,
    marginTop: spacing.xs,
    lineHeight: 17,
  },
  chipSeparator: {
    height: 1,
    backgroundColor: colors.border,
    marginTop: spacing.sm,
    marginBottom: spacing.sm,
  },
  chipTimeRow: {
    flexDirection: 'row',
    gap: spacing.lg,
  },
  chipTimeItem: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  chipTimeIcon: {
    fontSize: 13,
    marginRight: spacing.xs,
  },
  chipTimeLabel: {
    color: colors.accent,
    fontSize: fonts.sizes.xs,
    fontWeight: fonts.weights.medium,
  },
  catBadge: {
    fontSize: 16,
    marginLeft: spacing.sm,
    alignSelf: 'flex-start',
    marginTop: 2,
  },
  priorityBadge: {
    backgroundColor: 'rgba(0, 229, 255, 0.15)',
    borderRadius: borderRadius.full,
    paddingHorizontal: 6,
    paddingVertical: 2,
    marginLeft: spacing.sm,
  },
  priorityBadgeText: {
    color: colors.accent,
    fontSize: 10,
  },

  // Custom
  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',
    marginBottom: spacing.xl,
  },
  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,
  },

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