import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Platform } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { Colors } from '../../constants/theme';
import { useRouter, usePathname, useSegments } from 'expo-router';

import { useAuthStore } from '../../store/authStore';

export function UnifiedBottomNav() {
  const router = useRouter();
  const pathname = usePathname();
  const segments = useSegments();
  const { user_id } = useAuthStore();
  const isLoggedIn = !!user_id;

  const isActive = (path: string) => {
    // segments[0] let us differentiate between similar pathnames (e.g '/' in (public) vs '/' in (drawer))
    const isPublic = segments[0] === '(public)';
    const isDrawer = segments[0] === '(drawer)' || segments[0] === '(auth)';

    if (path === 'search') return isPublic && pathname.includes('/services');
    if (path === 'home') return (isPublic && !pathname.includes('/services')) || !segments[0];
    if (path === 'chat') return isDrawer && pathname.includes('/chat');
    if (path === 'account') return isDrawer && !pathname.includes('/chat');
    return false;
  };

  const getTabColor = (tab: string) => isActive(tab) ? Colors.light.primary : Colors.light.textMuted;
  const getIconName = (tab: string, icon: string) => isActive(tab) ? icon as any : (icon + '-outline') as any;

  const handleHomePress = () => {
    if (!segments[0] || segments[0] !== '(public)') {
      router.navigate('/(public)' as any);
    } else {
      if (router.canGoBack()) {
        router.dismissAll();
      }
    }
  };

  const handleChatPress = () => {
    if (isLoggedIn) {
      router.navigate('/(drawer)/(tabs)/chat' as any);
    } else {
      router.navigate('/login' as any);
    }
  };

  const handleAccountPress = () => {
    if (isLoggedIn) {
      router.navigate('/(drawer)/(tabs)' as any);
    } else {
      router.navigate('/login' as any);
    }
  };

  const handlePublishPress = () => {
    if (isLoggedIn) {
      router.navigate('/(drawer)/(tabs)' as any);
    } else {
      router.navigate('/login' as any);
    }
  };

  const insets = useSafeAreaInsets();
  const bottomPad = Math.max(0, (insets.bottom > 0 ? insets.bottom : 16) - 8);

  return (
    <View style={[styles.container, { paddingBottom: bottomPad, height: 60 + bottomPad }]}>
      <TouchableOpacity style={styles.tab} onPress={handleHomePress}>
        <Ionicons name={getIconName('home', 'home')} size={24} color={getTabColor('home')} />
        <Text style={[styles.label, { color: getTabColor('home'), fontWeight: isActive('home') ? 'bold' : 'normal' }]}>Home</Text>
      </TouchableOpacity>
      
      <TouchableOpacity style={styles.tab} onPress={() => router.push('/(public)/services?focus=search' as any)}>
        <Ionicons name={getIconName('search', 'search')} size={24} color={getTabColor('search')} />
        <Text style={[styles.label, { color: getTabColor('search'), fontWeight: isActive('search') ? 'bold' : 'normal' }]}>Pesquisa</Text>
      </TouchableOpacity>
      
      {/* Botão circular de publicação/acção central (Pinkish) */}
      <View style={styles.publishWrapper}>
        <TouchableOpacity style={styles.publishBtn} onPress={handlePublishPress}>
          <Ionicons name="add" size={32} color="#fff" />
        </TouchableOpacity>
      </View>
      
      <TouchableOpacity style={styles.tab} onPress={handleChatPress}>
        <Ionicons name={getIconName('chat', 'chatbubbles')} size={24} color={getTabColor('chat')} />
        <Text style={[styles.label, { color: getTabColor('chat'), fontWeight: isActive('chat') ? 'bold' : 'normal' }]}>Chat</Text>
      </TouchableOpacity>
      
      <TouchableOpacity style={styles.tab} onPress={handleAccountPress}>
        <Ionicons name={getIconName('account', 'person')} size={24} color={getTabColor('account')} />
        <Text style={[styles.label, { color: getTabColor('account'), fontWeight: isActive('account') ? 'bold' : 'normal' }]}>Conta</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    height: 60,
    backgroundColor: '#fff',
    borderTopWidth: 1,
    borderTopColor: '#f0f0f0',
    justifyContent: 'space-around',
    alignItems: 'center',
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    elevation: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: -2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  tab: {
    alignItems: 'center',
    justifyContent: 'center',
    flex: 1,
  },
  label: {
    fontSize: 10,
    marginTop: 2,
    color: Colors.light.textMuted,
  },
  publishWrapper: {
    flex: 1,
    alignItems: 'center',
  },
  publishBtn: {
    width: 56,
    height: 56,
    backgroundColor: Colors.light.primary,
    borderRadius: 28,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: -30, // Elevar o botão
    elevation: 5,
    shadowColor: Colors.light.primary,
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
  }
});
