import React, { useEffect, useState } from 'react';
import { 
  View, 
  Text, 
  StyleSheet, 
  FlatList, 
  ScrollView, 
  ActivityIndicator, 
  RefreshControl,
  TouchableOpacity
} from 'react-native';
import { useRouter, Stack } from 'expo-router';
import { Colors } from '../../constants/theme';
import { CategoryCard } from '../../components/home/CategoryCard';
import { ServiceCard } from '../../components/home/ServiceCard';
import { AdCarousel } from '../../components/home/AdCarousel';
import { UnifiedBottomNav } from '../../components/home/UnifiedBottomNav';
import api from '../../services/api';
import { Category, Service } from '../../types';

export default function HomeScreen() {
  const router = useRouter();
  const [categories, setCategories] = useState<Category[]>([]);
  const [featuredServices, setFeaturedServices] = useState<Service[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const fetchData = async () => {
    try {
      const [catRes, serRes] = await Promise.all([
        api.get('/categories?is_mobile=yes'),
        api.get('/services?is_mobile=yes')
      ]);

      // Mapeamento dos dados reais da API.
      // Categoria: { code: 200, data: [ { id, name, ... } ] }
      // Serviços (Paginated): { code: 200, data: { current_page, data: [ { id, ... } ] } }
      const cats = catRes.data?.data || [];
      const srvs = serRes.data?.data?.data || serRes.data?.data || [];
      
      setCategories(cats);
      setFeaturedServices(srvs);
    } catch (error) {
      console.error('Error fetching home data:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

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

  const onRefresh = () => {
    setRefreshing(true);
    fetchData();
  };

  const handleCategoryPress = (slug: string) => {
    router.push(`/(public)/category/${slug}`);
  };

  const handleServicePress = (slug: string) => {
    router.push(`/(public)/service/${slug}`);
  };

  const handleSeeAllServices = () => {
    router.push('/(public)/services' as any);
  };

  if (loading && !refreshing) {
    return (
      <View style={styles.loaderContainer}>
        <ActivityIndicator size="large" color={Colors.light.primary} />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <Stack.Screen 
        options={{ 
          headerShown: true, 
          title: 'E-Concerto', 
          headerTitleAlign: 'center',
          headerBackVisible: false,
          headerLeft: () => null 
        }} 
      />
      <AdCarousel />
      
      <ScrollView 
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}
        showsVerticalScrollIndicator={false}
      >
        {/* Categories Section */}
        <View style={styles.sectionHeader}>
          <Text style={styles.sectionTitle}>Categorias</Text>
        </View>
        
        <FlatList
          horizontal
          data={categories}
          keyExtractor={(item) => item.id.toString()}
          renderItem={({ item }) => (
            <CategoryCard category={item} onPress={handleCategoryPress} />
          )}
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={styles.categoryList}
        />

        {/* Featured Services */}
        <View style={styles.sectionHeader}>
          <Text style={styles.sectionTitle}>Serviços em Destaque</Text>
          <TouchableOpacity onPress={handleSeeAllServices}>
            <Text style={styles.seeAll}>Ver Tudo →</Text>
          </TouchableOpacity>
        </View>
        
        <View style={styles.servicesGrid}>
          {featuredServices.map((service) => (
            <ServiceCard 
              key={service.id} 
              service={service} 
              onPress={handleServicePress} 
            />
          ))}
        </View>

        {/* Placeholder for Latest Ads */}
        <View style={styles.footerSpace} />
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  loaderContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 15,
    marginTop: 20,
    marginBottom: 10,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: Colors.light.text,
  },
  seeAll: {
    fontSize: 14,
    color: Colors.light.primary,
  },
  categoryList: {
    paddingLeft: 15,
    paddingBottom: 5,
  },
  servicesGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    paddingHorizontal: 15,
  },
  footerSpace: {
    height: 100,
  },
  loginFab: {
    position: 'absolute',
    bottom: 20,
    right: 20,
    backgroundColor: Colors.light.primary,
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderRadius: 30,
    elevation: 5,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
  },
  loginFabText: {
    color: '#fff',
    fontWeight: 'bold',
    fontSize: 14,
  }
});
