
import { Ionicons, MaterialCommunityIcons, MaterialIcons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import * as SecureStore from 'expo-secure-store';
import React, { useEffect, useState } from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";

const PRIMARY = '#A24BFA';
const BG = '#0c0a0a';

export default function Profile() {
  const [user, setUser] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  useEffect(() => {
    fetchUser();
  }, []);

  async function fetchUser() {
    setLoading(true);
    try {
      const token = await SecureStore.getItemAsync('token');
      if (!token) {
        throw new Error('Nincs elmentett token, kérlek jelentkezz be újra!');
      }
      const response = await fetch('https://menuapi.devbeni.lol/api/@me', {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json',
        },
      });
      const data = await response.json();
      if (!data || !data.data || !data.data.Data) {
        setUser(null);
        return;
      }
      setUser(data.data.Data);
    } catch (e) {
      setUser(null);
    } finally {
      setLoading(false);
    }
  }

  async function handleLogout() {
    await SecureStore.deleteItemAsync('token');
    await SecureStore.deleteItemAsync('email');
    await SecureStore.deleteItemAsync('password');
    await SecureStore.deleteItemAsync('fullName');
    await SecureStore.deleteItemAsync('userId');
    router.replace('/');
  }

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Profil</Text>
      <View style={styles.card}>
        <Text style={styles.label}>Név:</Text>
        <Text style={styles.value}>{user?.FullName || '-'}</Text>
        <Text style={styles.label}>UserID:</Text>
        <Text style={styles.value}>{user?.UserID || '-'}</Text>
        <Text style={styles.label}>Szerepkör:</Text>
        <Text style={styles.value}>{user?.RoleCode || '-'}</Text>
        <Text style={styles.label}>Étterem:</Text>
        <Text style={styles.value}>{user?.RestaurantName || '-'}</Text>
        <TouchableOpacity style={styles.logoutButton} onPress={handleLogout}>
          <Text style={styles.logoutText}>Kijelentkezés</Text>
        </TouchableOpacity>
      </View>
      <View style={styles.navBar}>
        <NavBar activeTab="profile" />
      </View>
    </View>
  );
}

function NavBar({ activeTab }: { activeTab: string }) {
  const router = useRouter();
  return (
    <View style={styles.navBar}>
      <TouchableOpacity style={styles.navItem} onPress={() => router.push('/profile')}>
        <MaterialIcons name="person" size={28} color={activeTab === 'profile' ? PRIMARY : '#bdbdbd'} />
        <Text style={[styles.navLabel, { color: activeTab === 'profile' ? PRIMARY : '#bdbdbd' }]}>Profilom</Text>
      </TouchableOpacity>
      <TouchableOpacity style={styles.navItem} onPress={() => router.push('/schedule')}>
        <MaterialCommunityIcons name="calendar-month" size={28} color={activeTab === 'schedule' ? PRIMARY : '#bdbdbd'} />
        <Text style={[styles.navLabel, { color: activeTab === 'schedule' ? PRIMARY : '#bdbdbd' }]}>Beosztás</Text>
      </TouchableOpacity>
      <TouchableOpacity style={styles.navItem} onPress={() => router.push('/requests')}>
        <Ionicons name="mail" size={28} color={activeTab === 'requests' ? PRIMARY : '#bdbdbd'} />
        <Text style={[styles.navLabel, { color: activeTab === 'requests' ? PRIMARY : '#bdbdbd' }]}>Kérelmek</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: BG,
    justifyContent: 'center',
    alignItems: 'center',
    paddingBottom: 64,
  },
  title: {
    color: '#fff',
    fontWeight: 'bold',
    fontSize: 28,
    textAlign: 'center',
    marginBottom: 24,
    marginTop: 32,
  },
  card: {
    backgroundColor: 'rgba(24, 20, 28, 0.95)',
    borderRadius: 24,
    padding: 32,
    width: '90%',
    maxWidth: 400,
    shadowColor: '#000',
    shadowOpacity: 0.3,
    shadowRadius: 24,
    shadowOffset: { width: 0, height: 8 },
    elevation: 8,
    marginBottom: 32,
  },
  label: {
    color: '#bdbdbd',
    fontSize: 16,
    marginTop: 12,
    fontWeight: 'bold',
  },
  value: {
    color: PRIMARY,
    fontSize: 18,
    marginBottom: 8,
  },
  navBar: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    backgroundColor: 'rgba(24, 20, 28, 0.98)',
    borderTopWidth: 1,
    borderTopColor: '#222',
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    height: 64,
    paddingHorizontal: 16,
  },
  navItem: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  navLabel: {
    fontSize: 13,
    marginTop: 2,
    fontWeight: 'bold',
  },
  logoutButton: {
    backgroundColor: PRIMARY,
    borderRadius: 12,
    paddingVertical: 16,
    alignItems: 'center',
    marginTop: 32,
    shadowColor: PRIMARY,
    shadowOpacity: 0.3,
    shadowRadius: 8,
    shadowOffset: { width: 0, height: 2 },
    elevation: 2,
  },
  logoutText: {
    color: '#fff',
    fontWeight: 'bold',
    fontSize: 18,
    letterSpacing: 1,
  },
});
