import { Ionicons } from '@expo/vector-icons';
import AsyncStorage from '@react-native-async-storage/async-storage';
import DateTimePicker from '@react-native-community/datetimepicker';
import { DrawerActions, useNavigation } from '@react-navigation/native';
import axios from 'axios';
import { format } from 'date-fns';
import React, { useEffect, useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  FlatList,
  Image,
  Platform,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import { fetchGames } from '../src/api/api';

const BASE_URL = 'http://192.168.21.70/api';
const TOKEN_KEY = 'api_token';

export default function HomeScreen() {
  const [date, setDate] = useState(new Date());
  const [games, setGames] = useState([]);
  const [loading, setLoading] = useState(false);
  const [showPicker, setShowPicker] = useState(false);
  const [expandedId, setExpandedId] = useState(null);
  const [details, setDetails] = useState({});
  const navigation = useNavigation();

  const formattedDateForURL = format(date, 'yyyyMMdd');

  const loadGames = async (selectedDate) => {
    setLoading(true);
    try {
      const formattedDate = format(selectedDate, 'yyyy-MM-dd');
      const data = await fetchGames(formattedDate);
      setGames(data);
    } catch (error) {
      console.error('❌ Error al cargar juegos:', error);
      Alert.alert('Error', 'No se pudieron cargar los juegos.');
    } finally {
      setLoading(false);
    }
  };

  const fetchDetails = async (gameId) => {
    try {
      const token = await AsyncStorage.getItem(TOKEN_KEY);
      const response = await axios.get(`${BASE_URL}/gamesDetail?game=${gameId}`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      setDetails(prev => ({ ...prev, [gameId]: response.data[0] }));
    } catch (error) {
      console.error('Error fetching game details:', error);
    }
  };

  useEffect(() => {
    loadGames(date);
  }, []);

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

  const getLogoUrl = (rotation) => `https://www.sportsbettingonline.ag/engine/sbo/images/live_team_logos/${formattedDateForURL}/${rotation}.jpg`;
  const getPitcherImg = (id) => `https://a.espncdn.com/combiner/i?img=/i/headshots/mlb/players/full/${id}.png`;

  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" />
      ) : (
        <FlatList
          data={games}
          keyExtractor={(item) => item.id.toString()}
          renderItem={({ item }) => (
            <View style={styles.card}>
              <View style={styles.row}>
                <Image source={{ uri: getLogoUrl(item.away_rotation) }} style={styles.logo} />
                <Text style={styles.teamText}>{item.away}</Text>
                <Text style={styles.time}>{item.time}</Text>
              </View>
              <View style={styles.row}>
                <Image source={{ uri: getLogoUrl(item.home_rotation) }} style={styles.logo} />
                <Text style={styles.teamText}>{item.home}</Text>
              </View>
              <TouchableOpacity
                style={styles.expandButton}
                onPress={() => {
                  if (!details[item.id]) fetchDetails(item.id);
                  setExpandedId(expandedId === item.id ? null : item.id);
                }}
              >
                <Text style={styles.expandText}>{expandedId === item.id ? 'Ocultar ⬆️' : 'Ver más ⬇️'}</Text>
              </TouchableOpacity>

              {expandedId === item.id && details[item.id] && (
                <View style={styles.detailSection}>
                  <View style={styles.pitcherRow}>
                    <Image source={{ uri: getPitcherImg(details[item.id].p_away_espn) }} style={styles.pitcherImg} />
                    <View>
                      <Text style={styles.statText}>{details[item.id].p_away}</Text>
                      <Text style={styles.statText}>ERA: {details[item.id].p_away_era_avg}</Text>
                      <Text style={styles.statText}>WHIP: {details[item.id].p_away_whip_avg}</Text>
                      {details[item.id].p_away_throw === 'L' && (
                        <Text style={styles.leftyText}>Lefty</Text>
                      )}
                    </View>
                  </View>
                  <View style={styles.pitcherRow}>
                    <Image source={{ uri: getPitcherImg(details[item.id].p_home_espn) }} style={styles.pitcherImg} />
                    <View>
                      <Text style={styles.statText}>{details[item.id].p_home}</Text>
                      <Text style={styles.statText}>ERA: {details[item.id].p_home_era_avg}</Text>
                      <Text style={styles.statText}>WHIP: {details[item.id].p_home_whip_avg}</Text>
                      {details[item.id].p_home_throw === 'L' && (
                        <Text style={styles.leftyText}>Lefty</Text>
                      )}
                    </View>
                  </View>
                </View>
              )}
            </View>
          )}
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#000',
    padding: 16,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 16,
  },
  logoTop: {
    width: 36,
    height: 36,
    resizeMode: 'contain',
  },
  dateButton: {
    backgroundColor: '#222',
    padding: 12,
    borderRadius: 8,
    marginBottom: 16,
  },
  dateText: {
    color: '#0af',
    textAlign: 'center',
    fontSize: 16,
  },
  card: {
    backgroundColor: '#111',
    padding: 16,
    borderRadius: 10,
    marginBottom: 12,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
    justifyContent: 'space-between',
  },
  logo: {
    width: 30,
    height: 30,
    marginRight: 10,
    borderRadius: 5,
    backgroundColor: '#333',
  },
  teamText: {
    color: '#fff',
    flex: 1,
    fontSize: 15,
    fontWeight: 'bold',
  },
  time: {
    color: '#ccc',
    fontSize: 14,
    marginLeft: 10,
  },
  expandButton: {
    marginTop: 6,
  },
  expandText: {
    color: '#0af',
  },
  detailSection: {
    marginTop: 10,
    paddingTop: 10,
    borderTopColor: '#333',
    borderTopWidth: 1,
  },
  pitcherRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  pitcherImg: {
    width: 50,
    height: 50,
    borderRadius: 25,
    marginRight: 10,
  },
  statText: {
    color: '#ccc',
    fontSize: 13,
  },
  leftyText: {
    color: '#f88',
    fontSize: 13,
    fontStyle: 'italic',
  },
});
