// index.tsx
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createDrawerNavigator } from '@react-navigation/drawer';
import React, { useEffect, useState } from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context';

import { useNotificationListener } from '../hooks/useNotificationListener';
import { usePushNotifications } from '../hooks/usePushNotifications';
import { Category } from '../types/Category';
import { Item } from '../types/Item';
import { CustomDrawerContent } from './CustomDrawerContent';
import HomeScreen from './HomeScreen';

const STORAGE_KEY = 'notifications';
const API_KEY_STORAGE = 'api_key';
const API_URL = 'https://notifier.gansejunge.com';

const Drawer = createDrawerNavigator();




export default function App() {
	const [data, setData] = useState<Item[]>([]);
	const [selected, setSelected] = useState<Category>('home');
	const [apiKey, setApiKey] = useState<string | null>(null);
	const [tempKey, setTempKey] = useState('');

	const pushToken = usePushNotifications({
		apiKey,
		backendUrl: API_URL,
		appVersion: '1.0.0',
		locale: 'en-uk',
	});

	useEffect(() => {
		(async () => {
			const storedKey = await AsyncStorage.getItem(API_KEY_STORAGE);
			if (storedKey) setApiKey(storedKey);
		})();
	}, []);

	useEffect(() => {
		(async () => {
			try {
				const stored = await AsyncStorage.getItem(STORAGE_KEY);
				if (stored) setData(JSON.parse(stored));
			} catch (err) {
				console.error('Failed to load stored notifications:', err);
			}
		})();
	}, []);

	useNotificationListener((items: Item[]) => {
		setData(items);
	});

	const handleLogout = async () => {
		await AsyncStorage.removeItem(API_KEY_STORAGE);
		await AsyncStorage.removeItem(STORAGE_KEY);
		setApiKey(null);
		setData([]);
		setSelected('home');
	};

	if (!apiKey) {
		// Show API key entry screen before Drawer
		return (
			<SafeAreaProvider>
				<HomeScreen
					apiKey={apiKey}
					setApiKey={setApiKey}
					tempKey={tempKey}
					setTempKey={setTempKey}
				/>
			</SafeAreaProvider>
		);
	}

	return (
		<SafeAreaProvider>
				<Drawer.Navigator
					screenOptions={{
						drawerType: 'slide',
						drawerStyle: { width: 250 },
						headerShown: false,
					}}
					drawerContent={() => (
						<CustomDrawerContent
							selected={selected}
							setSelected={setSelected}
							handleLogout={handleLogout}
						/>
					)}
				>
					<Drawer.Screen name="Home">
						{() => (
							<HomeScreen
								selectedCategory={selected}
								onSelectCategory={setSelected}
								data={data}
							/>
						)}
					</Drawer.Screen>
				</Drawer.Navigator>
		</SafeAreaProvider>
	);
}
