import React, { useState, useRef } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Alert,
  Animated,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { AccountStackParamList } from '../../navigation/types';
import { COLORS, FONT_SIZE, SPACING, RADIUS, TEXT, SHADOWS } from '../../theme';
import { useTheme } from '../../theme';
import { PlanBadge, Button, Input, SecureInput } from '../../components/ui';
import { useToast } from '../../contexts/ToastContext';
import { authAPI, billingAPI } from '../../services/api';
import { useAuthStore } from '../../stores/authStore';
import { useThemeStore, ThemeMode } from '../../stores/themeStore';
import { useLanguageStore, AppLanguage } from '../../stores/languageStore';
import { useTranslation } from '../../i18n';

type Props = NativeStackScreenProps<AccountStackParamList, 'AccountHome'>;

const PLAN_FEATURES: Record<string, string[]> = {
  free: ['1 published chatbot', '3 docs/bot', '100 convos/mo', 'Llama 3.3 model'],
  starter: ['1 published chatbot', '10 docs/bot', '1,500 convos/mo', 'Telegram integration', 'Inbox & Leads'],
  business: ['3 published chatbots', '50 docs/bot', '5,000 convos/mo', 'All models', 'WhatsApp + Telegram'],
  agency: ['Unlimited chatbots', 'Unlimited docs', '20,000 convos/mo', 'Code export'],
  enterprise: ['Everything in Agency', 'Unlimited convos', 'Priority support'],
};

export function SettingsScreen({ navigation }: Props) {
  const { theme } = useTheme();
  const { t } = useTranslation();
  const toast = useToast();
  const qc = useQueryClient();
  const user = useAuthStore(s => s.user);
  const updateUser = useAuthStore(s => s.updateUser);
  const logout = useAuthStore(s => s.logout);

  const appLanguage = useLanguageStore(s => s.language);
  const setAppLanguage = useLanguageStore(s => s.setLanguage);

  const [companyName, setCompanyName] = useState(user?.company_name ?? '');
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [savingProfile, setSavingProfile] = useState(false);

  const LANGUAGE_OPTIONS: { key: AppLanguage; label: string; flag: string }[] = [
    { key: 'fr', label: 'Français', flag: '🇫🇷' },
    { key: 'en', label: 'English', flag: '🇬🇧' },
  ];

  const { data: subscription } = useQuery({
    queryKey: ['subscription'],
    queryFn: billingAPI.subscription,
  });

  const themeMode = useThemeStore(s => s.mode);
  const setThemeMode = useThemeStore(s => s.setMode);

  const THEME_OPTIONS: { key: ThemeMode; label: string; icon: string }[] = [
    { key: 'system', label: t.settings.theme_system, icon: '⚙️' },
    { key: 'light', label: t.settings.theme_light, icon: '☀️' },
    { key: 'dark', label: t.settings.theme_dark, icon: '🌙' },
  ];

  const handleSaveProfile = async () => {
    if (!companyName.trim()) {
      toast.error(t.settings.company_required);
      return;
    }
    setSavingProfile(true);
    try {
      const payload: any = { company_name: companyName.trim(), language: appLanguage };
      if (currentPassword && newPassword) {
        payload.current_password = currentPassword;
        payload.new_password = newPassword;
      }
      const updated = await authAPI.updateProfile(payload);
      updateUser(updated.user ?? { company_name: companyName.trim() });
      setCurrentPassword('');
      setNewPassword('');
      toast.success(t.settings.profile_updated);
    } catch (err: any) {
      toast.error(err?.response?.data?.detail ?? t.settings.update_failed);
    } finally {
      setSavingProfile(false);
    }
  };

  const handleLogout = () => {
    Alert.alert(t.settings.sign_out, t.settings.sign_out_confirm, [
      { text: t.common.cancel, style: 'cancel' },
      {
        text: t.settings.sign_out,
        style: 'destructive',
        onPress: async () => {
          try { await authAPI.logout(); } catch {}
          logout();
          qc.clear();
        },
      },
    ]);
  };

  const handleDeleteAccount = () => {
    Alert.alert(
      t.settings.delete_account,
      t.settings.delete_confirm,
      [
        { text: t.common.cancel, style: 'cancel' },
        {
          text: t.settings.delete_account,
          style: 'destructive',
          onPress: async () => {
            try {
              await authAPI.deleteAccount();
              logout();
              qc.clear();
            } catch (err: any) {
              toast.error(err?.response?.data?.detail ?? 'Failed to delete account');
            }
          },
        },
      ],
    );
  };

  const currentPlan = subscription?.plan ?? user?.plan ?? 'free';
  const planFeatures = PLAN_FEATURES[currentPlan] ?? [];

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.bg }]} edges={['bottom']}>
      <ScrollView contentContainerStyle={styles.scroll} showsVerticalScrollIndicator={false}>

        {/* User hero card */}
        <View style={[styles.heroCard, { backgroundColor: theme.surface, borderColor: theme.border }, SHADOWS.md]}>
          <View style={[styles.userAvatar, SHADOWS.primary]}>
            <Text style={styles.userAvatarText}>
              {(user?.email ?? 'U')[0].toUpperCase()}
            </Text>
          </View>
          <View style={styles.userInfo}>
            <Text style={[styles.userName, { color: theme.text }]}>{user?.company_name}</Text>
            <Text style={[styles.userEmail, { color: theme.textSecondary }]}>{user?.email}</Text>
            <PlanBadge plan={user?.plan ?? 'free'} />
          </View>
        </View>

        {/* Subscription */}
        <View style={[styles.section, { backgroundColor: theme.surface, borderColor: theme.border }, SHADOWS.sm]}>
          <Text style={[styles.sectionTitle, { color: theme.text }]}>{t.settings.subscription}</Text>

          <View style={styles.planRow}>
            <PlanBadge plan={currentPlan} />
            {subscription?.status && (
              <View style={[styles.statusPill, { backgroundColor: theme.bgSecondary }]}>
                <Text style={[styles.statusText, { color: theme.textSecondary }]}>{subscription.status}</Text>
              </View>
            )}
          </View>

          {subscription?.current_period_end && (
            <Text style={[styles.renewDate, { color: theme.textMuted }]}>
              Renews {new Date(subscription.current_period_end).toLocaleDateString()}
            </Text>
          )}

          <View style={[styles.featuresList, { borderTopColor: theme.borderLight }]}>
            {planFeatures.map(f => (
              <View key={f} style={styles.featureItem}>
                <Text style={[styles.featureCheck, { color: COLORS.success }]}>✓</Text>
                <Text style={[styles.featureText, { color: theme.textSecondary }]}>{f}</Text>
              </View>
            ))}
          </View>
        </View>

        {/* Quick nav */}
        <View style={[styles.section, { backgroundColor: theme.surface, borderColor: theme.border }, SHADOWS.sm]}>
          <Text style={[styles.sectionTitle, { color: theme.text }]}>{t.settings.reports}</Text>
          <MenuRow icon="📊" label={t.settings.analytics} onPress={() => navigation.navigate('Analytics')} theme={theme} />
          <MenuRow icon="👥" label={t.settings.leads} onPress={() => navigation.navigate('Leads')} theme={theme} />
          <MenuRow icon="📣" label={t.settings.campaigns} onPress={() => navigation.navigate('Campaigns')} theme={theme} />
          <MenuRow icon="📅" label={t.settings.appointments} onPress={() => navigation.navigate('Appointments')} theme={theme} isLast />
        </View>

        {/* Appearance */}
        <View style={[styles.section, { backgroundColor: theme.surface, borderColor: theme.border }, SHADOWS.sm]}>
          <Text style={[styles.sectionTitle, { color: theme.text }]}>{t.settings.appearance}</Text>
          <View style={themeStyles.row}>
            {THEME_OPTIONS.map(opt => (
              <TouchableOpacity
                key={opt.key}
                style={[
                  themeStyles.pill,
                  { borderColor: themeMode === opt.key ? COLORS.primary : theme.border },
                  themeMode === opt.key && { backgroundColor: COLORS.primaryUltraLight },
                ]}
                onPress={() => setThemeMode(opt.key)}>
                <Text style={themeStyles.pillIcon}>{opt.icon}</Text>
                <Text style={[themeStyles.pillLabel, { color: themeMode === opt.key ? COLORS.primaryDark : theme.textSecondary }]}>
                  {opt.label}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>

        {/* Profile */}
        <View style={[styles.section, { backgroundColor: theme.surface, borderColor: theme.border }, SHADOWS.sm]}>
          <Text style={[styles.sectionTitle, { color: theme.text }]}>{t.settings.profile}</Text>
          <Input
            label={t.settings.company_label}
            value={companyName}
            onChangeText={setCompanyName}
            placeholder={t.settings.company_placeholder}
          />

          <View style={langStyles.field}>
            <Text style={[langStyles.label, { color: theme.text }]}>{t.settings.language_label}</Text>
            <View style={langStyles.row}>
              {LANGUAGE_OPTIONS.map(opt => (
                <TouchableOpacity
                  key={opt.key}
                  style={[
                    langStyles.pill,
                    { borderColor: appLanguage === opt.key ? COLORS.primary : theme.border },
                    appLanguage === opt.key && { backgroundColor: COLORS.primaryUltraLight },
                  ]}
                  onPress={() => setAppLanguage(opt.key)}>
                  <Text style={langStyles.flag}>{opt.flag}</Text>
                  <Text style={[langStyles.pillLabel, { color: appLanguage === opt.key ? COLORS.primaryDark : theme.textSecondary }]}>
                    {opt.label}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>

          <View style={[styles.divider, { borderTopColor: theme.borderLight }]}>
            <Text style={[styles.subTitle, { color: theme.textSecondary }]}>{t.settings.change_password}</Text>
          </View>

          <SecureInput
            label={t.settings.current_password}
            value={currentPassword}
            onChangeText={setCurrentPassword}
            placeholder={t.settings.current_password}
          />
          <SecureInput
            label={t.settings.new_password}
            value={newPassword}
            onChangeText={setNewPassword}
            placeholder={t.settings.new_password}
          />
          <Button
            title={t.settings.save_profile}
            onPress={handleSaveProfile}
            loading={savingProfile}
            size="md"
          />
        </View>

        {/* Account actions */}
        <View style={[styles.section, styles.dangerSection, { backgroundColor: theme.surface, borderColor: '#fee2e2' }, SHADOWS.sm]}>
          <Text style={[styles.sectionTitle, { color: COLORS.error }]}>{t.settings.account}</Text>
          <Button title={t.settings.sign_out} variant="outline" onPress={handleLogout} fullWidth />
          <Button title={t.settings.delete_account} variant="danger" onPress={handleDeleteAccount} fullWidth />
        </View>

        <Text style={[styles.version, { color: theme.textMuted }]}>Contexta v1.0.0</Text>
      </ScrollView>
    </SafeAreaView>
  );
}

function MenuRow({
  icon,
  label,
  onPress,
  theme,
  isLast,
}: {
  icon: string;
  label: string;
  onPress: () => void;
  theme: any;
  isLast?: boolean;
}) {
  const scale = useRef(new Animated.Value(1)).current;

  const onPressIn = () => Animated.spring(scale, { toValue: 0.98, useNativeDriver: true, speed: 60 }).start();
  const onPressOut = () => Animated.spring(scale, { toValue: 1, useNativeDriver: true, speed: 30, bounciness: 4 }).start();

  return (
    <TouchableOpacity onPress={onPress} onPressIn={onPressIn} onPressOut={onPressOut} activeOpacity={1}>
      <Animated.View
        style={[
          menuStyles.row,
          !isLast && { borderBottomWidth: 1, borderBottomColor: theme.borderLight },
          { transform: [{ scale }] },
        ]}>
        <View style={[menuStyles.iconBg, { backgroundColor: theme.bgSecondary }]}>
          <Text style={menuStyles.icon}>{icon}</Text>
        </View>
        <Text style={[menuStyles.label, { color: theme.text }]}>{label}</Text>
        <Text style={[menuStyles.chevron, { color: theme.textMuted }]}>›</Text>
      </Animated.View>
    </TouchableOpacity>
  );
}

const menuStyles = StyleSheet.create({
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: SPACING.md,
    gap: SPACING.md,
  },
  iconBg: { width: 36, height: 36, borderRadius: RADIUS.md, alignItems: 'center', justifyContent: 'center' },
  icon: { fontSize: 18 },
  label: { flex: 1, ...TEXT.body },
  chevron: { fontSize: 20, fontWeight: '300' },
});

const styles = StyleSheet.create({
  safe: { flex: 1 },
  scroll: { padding: SPACING.lg, gap: SPACING.md, paddingBottom: SPACING.xxxl },

  heroCard: {
    borderRadius: RADIUS.xxl,
    padding: SPACING.xl,
    borderWidth: 1,
    flexDirection: 'row',
    alignItems: 'center',
    gap: SPACING.lg,
  },
  userAvatar: {
    width: 64,
    height: 64,
    borderRadius: RADIUS.full,
    backgroundColor: COLORS.primary,
    alignItems: 'center',
    justifyContent: 'center',
    flexShrink: 0,
  },
  userAvatarText: { color: COLORS.white, fontSize: FONT_SIZE.xxl, fontWeight: '800' },
  userInfo: { flex: 1, gap: SPACING.xs },
  userName: { ...TEXT.h4 },
  userEmail: { ...TEXT.small },

  section: {
    borderRadius: RADIUS.xl,
    borderWidth: 1,
    padding: SPACING.lg,
    gap: SPACING.md,
  },
  dangerSection: {},
  sectionTitle: { ...TEXT.h4 },

  planRow: { flexDirection: 'row', alignItems: 'center', gap: SPACING.sm },
  statusPill: { borderRadius: RADIUS.full, paddingVertical: 3, paddingHorizontal: SPACING.sm },
  statusText: { fontSize: FONT_SIZE.xs, fontWeight: '500', textTransform: 'capitalize' },
  renewDate: { ...TEXT.small },

  featuresList: { borderTopWidth: 1, paddingTop: SPACING.md, gap: SPACING.sm },
  featureItem: { flexDirection: 'row', alignItems: 'flex-start', gap: SPACING.xs },
  featureCheck: { fontSize: FONT_SIZE.sm, fontWeight: '700', lineHeight: 20 },
  featureText: { ...TEXT.small, flex: 1, lineHeight: 20 },

  divider: { borderTopWidth: 1, paddingTop: SPACING.sm },
  subTitle: { ...TEXT.smallM },

  version: { ...TEXT.caption, textAlign: 'center' },
});

const langStyles = StyleSheet.create({
  field: { gap: SPACING.xs },
  label: { fontSize: FONT_SIZE.sm, fontWeight: '500' },
  row: { flexDirection: 'row', gap: SPACING.sm },
  pill: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: SPACING.xs,
    borderWidth: 1.5,
    borderRadius: RADIUS.lg,
    paddingVertical: SPACING.sm,
  },
  flag: { fontSize: 18 },
  pillLabel: { fontSize: FONT_SIZE.sm, fontWeight: '600' },
});

const themeStyles = StyleSheet.create({
  row: { flexDirection: 'row', gap: SPACING.sm },
  pill: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: SPACING.xs,
    borderWidth: 1.5,
    borderRadius: RADIUS.lg,
    paddingVertical: SPACING.sm,
  },
  pillIcon: { fontSize: 16 },
  pillLabel: { fontSize: FONT_SIZE.sm, fontWeight: '600' },
});
