import React, { useCallback } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import { Card } from '../../components/ui';
import { useAuthStore } from '../../stores/auth.store';
import type { MoreStackParamList } from '../../app/navigation';

type MoreNav = NativeStackNavigationProp<MoreStackParamList, 'MoreMain'>;

export function MoreScreen(): React.JSX.Element {
  const styles = createStyles();
  const { user, logout } = useAuthStore();
  const navigation = useNavigation<MoreNav>();

  const handleLogout = useCallback(() => {
    logout();
  }, [logout]);

  const roleLabels: Record<string, string> = {
    TRAINER: 'Тренер',
    COORDINATOR: 'Координатор',
    MANAGER: 'Фитнес-менеджер',
    RECEPTIONIST: 'Администратор',
    CLUB_ADMIN: 'Админ клуба',
    SUPER_ADMIN: 'Суперадмин',
  };

  return (
    <View style={styles.container}>
      {user && (
        <Card style={styles.profileCard}>
          <Text style={styles.profileName}>{`${user.firstName} ${user.lastName}`}</Text>
          <Text style={styles.profileRole}>{roleLabels[user.role] ?? user.role}</Text>
        </Card>
      )}

      <View style={styles.menu}>
        <MenuItem label="Статистика" onPress={() => navigation.navigate('Stats')} />
        <MenuItem label="Рейтинг" onPress={() => navigation.navigate('Rating')} />
        <MenuItem label="Продажи" onPress={() => navigation.navigate('SalesList')} />
        {(user?.role === 'COORDINATOR' || user?.role === 'MANAGER') && (
          <MenuItem label="Координатор" onPress={() => navigation.navigate('Coordinator')} />
        )}
        <MenuItem label="Мои записи" onPress={() => navigation.navigate('BookingList')} />
        {(user?.role === 'COORDINATOR' ||
          user?.role === 'MANAGER' ||
          user?.role === 'CLUB_ADMIN') && (
          <MenuItem label="Групповые занятия" onPress={() => navigation.navigate('GroupEvents')} />
        )}
        <MenuItem label="Звонки" onPress={() => navigation.navigate('CallLog')} />
        <MenuItem label="График работы" onPress={() => navigation.navigate('WorkSchedule')} />
        <MenuItem label="Уведомления" onPress={() => navigation.navigate('Notifications')} />
        <MenuItem label="Спящие клиенты" onPress={() => navigation.navigate('SleepingClients')} />
      </View>

      <TouchableOpacity style={styles.logoutButton} onPress={handleLogout}>
        <Text style={styles.logoutText}>Выйти</Text>
      </TouchableOpacity>
    </View>
  );
}

function MenuItem({ label, onPress }: { label: string; onPress?: () => void }): React.JSX.Element {
  const styles = createStyles();
  return (
    <TouchableOpacity style={styles.menuItem} activeOpacity={0.7} onPress={onPress}>
      <Text style={styles.menuItemText}>{label}</Text>
      <Text style={styles.menuItemArrow}>{'>'}</Text>
    </TouchableOpacity>
  );
}

const createStyles = () =>
  StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background,
      padding: spacing.lg,
    },
    profileCard: {
      marginBottom: spacing.xl,
    },
    profileName: {
      ...typography.subtitle,
      color: colors.text,
    },
    profileRole: {
      ...typography.bodySmall,
      color: colors.textSecondary,
      marginTop: spacing.xs,
    },
    menu: {
      backgroundColor: colors.white,
      borderRadius: 12,
      overflow: 'hidden',
    },
    menuItem: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      paddingVertical: spacing.lg,
      paddingHorizontal: spacing.lg,
      borderBottomWidth: 1,
      borderBottomColor: colors.border,
    },
    menuItemText: {
      ...typography.body,
      color: colors.text,
    },
    menuItemArrow: {
      ...typography.body,
      color: colors.textMuted,
    },
    logoutButton: {
      marginTop: spacing.xxxl,
      alignItems: 'center',
      paddingVertical: spacing.lg,
    },
    logoutText: {
      ...typography.body,
      color: colors.error,
      fontWeight: '600',
    },
  });
