import React, { useCallback } from 'react';
import { View, Text, TouchableOpacity, ScrollView } from 'react-native';
import {
  useNavigation,
  CompositeNavigationProp,
  useFocusEffect,
} from '@react-navigation/native';
import { BottomTabNavigationProp } from '@react-navigation/bottom-tabs';
import { StackNavigationProp } from '@react-navigation/stack';
import { getStyles } from './accountScreen.styles';
import { Header, PrimaryButton } from '@components';
import { useAppTheme } from '@theme';
import { AppStackParamList } from '../../../navigation/appStack';
import { MainTabParamList } from '../../../navigation/mainTabNavigator';
import { logoutUser, useAppDispatch, useAppSelector } from '@store';
import { getWalletBalanceThunk } from './thunk';

type AccountNavProp = CompositeNavigationProp<
  BottomTabNavigationProp<MainTabParamList, 'AccountScreen'>,
  StackNavigationProp<AppStackParamList>
>;

interface MenuItemData {
  icon: string;
  label: string;
  subLabel: string;
  tint: string;
  onPress?: (navigation: AccountNavProp) => void;
}

interface MenuSectionData {
  title: string;
  items: MenuItemData[];
}

const MENU_SECTIONS: MenuSectionData[] = [
  {
    title: 'Account',
    items: [
      {
        icon: '📍',
        label: 'My Addresses',
        subLabel: 'Manage delivery addresses',
        tint: '#FDECEA',
      },
      {
        icon: '💳',
        label: 'Wallet',
        subLabel: 'Cards, UPI & wallets',
        tint: '#FFF4E5',
        onPress: navigation => navigation.navigate('WalletScreen'),
      },
      {
        icon: '🔔',
        label: 'Notifications',
        subLabel: 'Alerts, offers & updates',
        tint: '#FFF9DB',
      },
    ],
  },
  {
    title: 'Support & Legal',
    items: [
      {
        icon: '❓',
        label: 'Help & Support',
        subLabel: 'FAQs and contact us',
        tint: '#EAF4FF',
        onPress: navigation => navigation.navigate('HelpSupportScreen'),
      },
      {
        icon: '📋',
        label: 'Terms & Conditions',
        subLabel: 'Our terms of service',
        tint: '#F1F0FF',
      },
      {
        icon: '🔒',
        label: 'Privacy Policy',
        subLabel: 'How we handle your data',
        tint: '#E9F7EF',
      },
    ],
  },
];

export const AccountScreen: React.FC = () => {
  const { colors } = useAppTheme();
  const styles = getStyles(colors);
  const dispatch = useAppDispatch();
  const navigation = useNavigation<AccountNavProp>();
  const user = useAppSelector(
    state => state.customerProfile.customerDetails?.user,
  );
  const { wallet } = useAppSelector(state => state.account);

  useFocusEffect(
    useCallback(() => {
      dispatch(getWalletBalanceThunk());
    }, []),
  );

  // TODO: wire these to real selectors once order/wallet state is available.
  // const ordersCount = user?.ordersCount ?? 0;
  // const savedAddressesCount = user?.addressesCount ?? 0;
  // const walletBalance = user?.walletBalance ?? 0;

  return (
    <View style={styles.container}>
      <Header title="Account" />
      <ScrollView
        contentContainerStyle={styles.content}
        showsVerticalScrollIndicator={false}
      >
        {/* Profile card */}
        <View style={styles.profileCard}>
          <View style={styles.avatarWrap}>
            <View style={styles.avatar}>
              <Text style={styles.avatarText}>
                {user?.name?.charAt(0)?.toUpperCase() || 'U'}
              </Text>
            </View>
            <TouchableOpacity
              style={styles.editAvatarBadge}
              activeOpacity={0.7}
            >
              <Text style={styles.editAvatarIcon}>✏️</Text>
            </TouchableOpacity>
          </View>

          <Text style={styles.profileName}>{user?.name || 'User'}</Text>
          <View style={styles.profilePhoneRow}>
            <Text style={styles.profilePhoneIcon}>📞</Text>
            <Text style={styles.profilePhone}>
              {user?.phone || '+91 98765 43210'}
            </Text>
          </View>

          <TouchableOpacity
            style={styles.editProfileButton}
            activeOpacity={0.75}
          >
            <Text style={styles.editProfileButtonText}>Edit Profile</Text>
          </TouchableOpacity>
        </View>

        {/* Quick stats */}
        {/* <View style={styles.statsRow}>
          <View style={styles.statItem}>
            <Text style={styles.statValue}>{ordersCount}</Text>
            <Text style={styles.statLabel}>Orders</Text>
          </View>
          <View style={styles.statDivider} />
          <View style={styles.statItem}>
            <Text style={styles.statValue}>{savedAddressesCount}</Text>
            <Text style={styles.statLabel}>Addresses</Text>
          </View>
          <View style={styles.statDivider} />
          <View style={styles.statItem}>
            <Text style={styles.statValue}>₹{walletBalance}</Text>
            <Text style={styles.statLabel}>Wallet</Text>
          </View>
        </View> */}

        {/* Menu sections */}
        {MENU_SECTIONS.map(section => (
          <View key={section.title} style={styles.menuSection}>
            <Text style={styles.sectionLabel}>{section.title}</Text>
            <View style={styles.sectionCard}>
              {section.items.map((item, index) => {
                const isLast = index === section.items.length - 1;
                return (
                  <TouchableOpacity
                    key={item.label}
                    style={[styles.menuItem, !isLast && styles.menuItemDivider]}
                    activeOpacity={0.7}
                    onPress={() => item.onPress?.(navigation)}
                  >
                    <View
                      style={[
                        styles.menuIconBadge,
                        { backgroundColor: item.tint },
                      ]}
                    >
                      <Text style={styles.menuIcon}>{item.icon}</Text>
                    </View>
                    <View style={styles.menuTextWrap}>
                      <Text style={styles.menuLabel}>{item.label}</Text>
                      <Text style={styles.menuSubLabel}>{item.subLabel}</Text>
                    </View>
                    <View style={styles.menuArrowBadge}>
                      <Text style={styles.menuArrow}>{'>'}</Text>
                    </View>
                  </TouchableOpacity>
                );
              })}
            </View>
          </View>
        ))}

        {/* Logout */}
        <View style={styles.logoutSection}>
          <PrimaryButton
            title="Logout"
            onPress={() => dispatch(logoutUser())}
          />
          <Text style={styles.versionText}>App version 1.0.0</Text>
        </View>
      </ScrollView>
    </View>
  );
};
