import React, { useState } from 'react';
import { View, StyleSheet, TouchableOpacity, Switch, ScrollView } from 'react-native';
import Animated, { FadeIn } from 'react-native-reanimated';
import { Ionicons } from '@expo/vector-icons';
import * as Haptics from 'expo-haptics';
import { colors, spacing, radii, shadows } from '../../theme/tokens';
import { SafeScreen } from '../../components/layout/SafeScreen';
import { Header } from '../../components/layout/Header';
import { H1, Body, BodyMedium, Caption, Button, Input, Card } from '../../components/ui';
import { t } from '../../i18n';
import { useExpenseStore } from '../../store';
import type { ExpenseCategory } from '../../types';

const CATEGORIES: { key: ExpenseCategory; icon: keyof typeof Ionicons.glyphMap }[] = [
  { key: 'housing', icon: 'home-outline' },
  { key: 'groceries', icon: 'cart-outline' },
  { key: 'transport', icon: 'car-outline' },
  { key: 'childcare', icon: 'people-outline' },
  { key: 'health', icon: 'medical-outline' },
  { key: 'education', icon: 'school-outline' },
  { key: 'utilities', icon: 'flash-outline' },
  { key: 'insurance', icon: 'shield-outline' },
  { key: 'leisure', icon: 'game-controller-outline' },
  { key: 'clothing', icon: 'shirt-outline' },
  { key: 'savings', icon: 'trending-up-outline' },
  { key: 'other', icon: 'ellipsis-horizontal-outline' },
];

export function AddExpenseScreen({ navigation }: any) {
  const [amount, setAmount] = useState('');
  const [category, setCategory] = useState<ExpenseCategory | null>(null);
  const [note, setNote] = useState('');
  const [isCommon, setIsCommon] = useState(true);
  const addExpense = useExpenseStore((s) => s.addExpense);

  const handleSubmit = async () => {
    if (!amount || !category) return;
    try {
      await Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
    } catch {}
    await addExpense({
      householdId: 'demo',
      userId: 'user_a',
      amount: Number(amount),
      category,
      note,
      date: new Date().toISOString().split('T')[0],
      isCommon,
    });
    navigation.goBack();
  };

  return (
    <SafeScreen backgroundColor={colors.background}>
      <Header title={t('expense.title')} onBack={() => navigation.goBack()} />
      <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
        {/* Amount */}
        <Animated.View entering={FadeIn.duration(400)} style={styles.amountSection}>
          <Input
            label={t('expense.amount')}
            value={amount}
            onChangeText={setAmount}
            keyboardType="numeric"
            placeholder="0.00"
            icon={<Body color={colors.neutral[400]}>$</Body>}
          />
        </Animated.View>

        {/* Category */}
        <Caption style={styles.sectionLabel}>{t('expense.category')}</Caption>
        <View style={styles.categoryGrid}>
          {CATEGORIES.map((cat) => {
            const selected = category === cat.key;
            return (
              <TouchableOpacity
                key={cat.key}
                style={[styles.categoryBtn, selected && styles.categorySelected]}
                onPress={() => setCategory(cat.key)}
                accessibilityRole="radio"
                accessibilityState={{ selected }}
              >
                <Ionicons
                  name={cat.icon}
                  size={22}
                  color={selected ? colors.primary[600] : colors.neutral[500]}
                />
                <Caption
                  style={[styles.categoryLabel, selected && styles.categoryLabelSelected]}
                  numberOfLines={1}
                >
                  {t(`quiz.${cat.key === 'other' ? 'otherCategory' : cat.key}`)}
                </Caption>
              </TouchableOpacity>
            );
          })}
        </View>

        {/* Note */}
        <Input
          label={t('expense.note')}
          value={note}
          onChangeText={setNote}
          placeholder={t('expense.note')}
        />

        {/* Common toggle */}
        <Card style={styles.toggleCard}>
          <View style={styles.toggleRow}>
            <View style={styles.toggleInfo}>
              <Ionicons name="people-outline" size={20} color={colors.primary[500]} />
              <BodyMedium>{t('expense.isCommon')}</BodyMedium>
            </View>
            <Switch
              value={isCommon}
              onValueChange={setIsCommon}
              trackColor={{ false: colors.neutral[200], true: colors.primary[300] }}
              thumbColor={isCommon ? colors.primary[500] : colors.neutral[400]}
            />
          </View>
        </Card>

        <View style={styles.footer}>
          <Button
            title={t('expense.addExpense')}
            onPress={handleSubmit}
            fullWidth
            size="lg"
            disabled={!amount || !category}
          />
        </View>
      </ScrollView>
    </SafeScreen>
  );
}

const styles = StyleSheet.create({
  scrollContent: {
    paddingHorizontal: spacing.xl,
    paddingBottom: spacing['5xl'],
  },
  amountSection: {
    marginBottom: spacing.lg,
  },
  sectionLabel: {
    textTransform: 'uppercase',
    letterSpacing: 1,
    color: colors.neutral[500],
    marginBottom: spacing.md,
  },
  categoryGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: spacing.sm,
    marginBottom: spacing.xl,
  },
  categoryBtn: {
    width: '23%',
    aspectRatio: 1,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: radii.xl,
    backgroundColor: colors.surface,
    borderWidth: 1.5,
    borderColor: colors.neutral[200],
    padding: spacing.xs,
    ...shadows.sm,
  },
  categorySelected: {
    borderColor: colors.primary[500],
    backgroundColor: colors.primary[50],
  },
  categoryLabel: {
    marginTop: spacing.xs,
    fontSize: 10,
    textAlign: 'center',
  },
  categoryLabelSelected: {
    color: colors.primary[700],
    fontWeight: '600',
  },
  toggleCard: {
    padding: spacing.lg,
    marginBottom: spacing.xl,
  },
  toggleRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  toggleInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.md,
  },
  footer: {
    marginTop: spacing.md,
  },
});
