import { Ionicons } from '@expo/vector-icons';
import DateTimePicker from '@react-native-community/datetimepicker';
import { DrawerActions, useNavigation } from '@react-navigation/native';
import { format } from 'date-fns';
import React, { useState } from 'react';
import {
  ActivityIndicator,
  Image,
  Platform,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import useGames from '../../src/hooks/useGames';
import GameList from './GameList';
import { styles } from './HomeScreen.styles';

export default function HomeScreen() {
  const [showPicker, setShowPicker] = useState(false);
  const navigation = useNavigation();

  const {
    date,
    games,
    loading,
    expandedId,
    details,
    formattedDateForURL,
    setDate,
    setExpandedId,
    fetchDetails,
    loadGames
  } = useGames();

  const onDateChange = (_event, selectedDate) => {
    setShowPicker(false);
    if (selectedDate) {
      setDate(selectedDate);
      loadGames(selectedDate);
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.dispatch(DrawerActions.openDrawer())}>
          <Ionicons name="menu" size={28} color="#fff" />
        </TouchableOpacity>
        <Image source={require('../../assets/fire-ring.png')} style={styles.logoTop} />
      </View>

      <TouchableOpacity onPress={() => setShowPicker(true)} style={styles.dateButton}>
        <Text style={styles.dateText}>📅 {format(date, 'dd/MM/yyyy')}</Text>
      </TouchableOpacity>

      {showPicker && Platform.OS !== 'web' && (
        <DateTimePicker
          value={date}
          mode="date"
          display="default"
          onChange={onDateChange}
        />
      )}

      {loading ? (
        <ActivityIndicator size="large" color="#fff" />
      ) : (
        <GameList
          games={games}
          loading={loading}
          formattedDateForURL={formattedDateForURL}
          expandedId={expandedId}
          setExpandedId={setExpandedId}
          details={details}
          fetchDetails={fetchDetails}
        />
      )}
    </View>
  );
}
