import React, { useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Image } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import { Container, ConfirmModal } from '@/shared/components/ui';
import type { RootState } from '@/store/store';
import { useTheme } from '@/shared/styles/useTheme';
import { logout } from '@/modules/auth/store/authSlice';
import { setProfile, setProfileFromAuth } from '@/modules/profile/store/profileSlice';
import { selectUserDisplayName, selectUserEmail, selectUserRole, selectAuthUser } from '@/modules/profile/store/selectors';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { clearSelectedService } from '@/modules/integrations/store/integrationsSlice';

const ProfileScreen: React.FC = () => {
  const dispatch = useDispatch();
  const { colors, fonts } = useTheme();
  
  // Get user data using selectors
  const authUser = useSelector(selectAuthUser);
  const displayName = useSelector(selectUserDisplayName);
  const email = useSelector(selectUserEmail);
  const role = useSelector(selectUserRole);
  const { name } = useSelector((s: RootState) => s.profile);

  useEffect(() => {
    // Sync profile data with auth user data when available
    if (authUser && (!name || !email)) {
      dispatch(setProfileFromAuth(authUser));
    }
  }, [dispatch, authUser, name, email]);

  const [showLogout, setShowLogout] = React.useState(false);
  const handleLogout = () => setShowLogout(true);
  const handleConfirmLogout = () => {
    setShowLogout(false);
    dispatch(clearSelectedService());
    dispatch(logout());
  };
  const handleCancelLogout = () => setShowLogout(false);

  return (
    <Container>
      <View style={[styles.top, { backgroundColor: colors.background }]}> 
        {/* Avatar */}
        <View style={styles.avatarWrap}>
          <View style={[styles.avatarCircle, { backgroundColor: '#E5E7EB' }]}>
            {/* If you have an image, replace with <Image source={{ uri: ... }} style={styles.avatarImage}/> */}
            <Icon name="account" size={56} color={colors.primary} />
          </View>
          <View style={[styles.editBadge, { backgroundColor: colors.primary }]}>
            <Icon name="pencil" size={14} color={colors.surface} />
          </View>
        </View>

        {/* Name */}
        <Text style={[styles.displayName, { color: colors.text, fontFamily: fonts.bold }]}>
          {displayName}
        </Text>

        {/* Email pill */}
        <View style={[styles.emailPill, { backgroundColor: '#DFE9FF' }]}>
          <Text style={{ color: colors.text, fontFamily: fonts.regular, fontSize: 12 }}>
            {email}
          </Text>
        </View>

        {/* Role badge */}
        {role && (
          <View style={[styles.roleBadge, { backgroundColor: colors.primary }]}>
            <Text style={{ color: colors.surface, fontFamily: fonts.medium, fontSize: 12 }}>
              {role.toUpperCase()}
            </Text>
          </View>
        )}
      </View>

      {/* Settings card */}
      <View style={[styles.card, { backgroundColor: colors.surface, borderColor: colors.border }]}> 
        <MenuItem icon="pencil-outline" label="Edit Profile" onPress={() => {}} />
        <Separator color={colors.border} />
        <MenuItem icon="shield-lock-outline" label="Add Pin" onPress={() => {}} />
        <Separator color={colors.border} />
        <MenuItem icon="cog-outline" label="Settings" onPress={() => {}} />
        <Separator color={colors.border} />
        <MenuItem icon="account-plus-outline" label="Invite a friend" onPress={() => {}} />
        <Separator color={colors.border} />
        <MenuItem icon="logout" label="Logout" danger onPress={handleLogout} />
      </View>

      <ConfirmModal
        visible={showLogout}
        title="Logout"
        message="Are you sure you want to logout?"
        confirmText="Logout"
        cancelText="Cancel"
        onConfirm={handleConfirmLogout}
        onCancel={handleCancelLogout}
      />
    </Container>
  );
};

const styles = StyleSheet.create({
  top: {
    alignItems: 'center',
    paddingVertical: 32,
  },
  avatarWrap: {
    position: 'relative',
  },
  avatarCircle: {
    width: 104,
    height: 104,
    borderRadius: 52,
    alignItems: 'center',
    justifyContent: 'center',
    overflow: 'hidden',
  },
  avatarImage: {
    width: '100%',
    height: '100%',
  },
  editBadge: {
    position: 'absolute',
    right: -2,
    bottom: 2,
    width: 32,
    height: 32,
    borderRadius: 16,
    alignItems: 'center',
    justifyContent: 'center',
  },
  displayName: {
    fontSize: 22,
    marginTop: 14,
  },
  emailPill: {
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 14,
    marginTop: 10,
  },
  roleBadge: {
    paddingHorizontal: 16,
    paddingVertical: 6,
    borderRadius: 12,
    marginTop: 8,
  },
  card: {
    marginTop: 20,
    marginHorizontal: 16,
    borderRadius: 12,
    borderWidth: 1,
  },
});

// Helpers
interface MenuItemProps { icon: string; label: string; onPress: () => void; danger?: boolean }
const MenuItem: React.FC<MenuItemProps> = ({ icon, label, onPress, danger }) => {
  const { colors, fonts } = useTheme();
  return (
    <TouchableOpacity style={menuStyles.row} activeOpacity={0.8} onPress={onPress}>
      <View style={[menuStyles.left, danger && { opacity: 0.9 }]}>
        <Icon name={icon} size={18} color={danger ? '#EF4444' : colors.text} />
        <Text style={[menuStyles.label, { color: danger ? '#EF4444' : colors.text, fontFamily: fonts.regular }]}>{label}</Text>
      </View>
      <Icon name="chevron-right" size={20} color={danger ? '#EF4444' : colors.text} />
    </TouchableOpacity>
  );
};

const Separator: React.FC<{ color: string }> = ({ color }) => (
  <View style={{ height: 1, backgroundColor: color, opacity: 0.6 }} />
);

const menuStyles = StyleSheet.create({
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 14,
  },
  left: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  label: {
    marginLeft: 8,
    fontSize: 14,
  },
});

export default ProfileScreen;


