// app/Professor/Empresas/ListaEmpresasProfessor.tsx
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  ActivityIndicator,
  Animated,
  RefreshControl,
  SectionList,
  StatusBar,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { supabase } from '../../../lib/supabase';
import { useTheme } from '../../../themecontext';

export interface Empresa {
  id: number;
  nome: string;
  morada: string;
  tutor_nome: string;
  tutor_telefone: string;
  curso: string;
}

const ListaEmpresasProfessor = memo(() => {
  const { isDarkMode } = useTheme();
  const router = useRouter();
  const insets = useSafeAreaInsets();

  const [search, setSearch] = useState('');
  const [empresas, setEmpresas] = useState<Empresa[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  // ESTADOS DO TOAST
  const [toast, setToast] = useState<{ visible: boolean; message: string; type: 'error' | 'success' | 'info' }>({ visible: false, message: '', type: 'info' });
  const slideAnim = useRef(new Animated.Value(-100)).current;

  // Cores EPVC
  const azulEPVC = '#2390a6';
  const laranjaEPVC = '#E38E00';
  const erroCor = '#EF4444';
  const sucessoCor = '#10B981';

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0A0A0A' : '#F4F7FA', // Novo design
    card: isDarkMode ? '#161618' : '#FFFFFF',
    texto: isDarkMode ? '#F8FAFC' : '#1E293B',
    secundario: isDarkMode ? '#94A3B8' : '#64748B',
    azul: azulEPVC,
    laranja: laranjaEPVC,
    azulSuave: isDarkMode ? 'rgba(35, 144, 166, 0.15)' : '#E0F2F4',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
    vermelho: erroCor,
    verde: sucessoCor,
    inputFundo: isDarkMode ? '#252525' : '#FBFDFF',
    overlay: 'rgba(0, 0, 0, 0.6)',
  }), [isDarkMode]);

  const showToast = useCallback((message: string, type: 'error' | 'success' | 'info' = 'info') => {
    setToast({ visible: true, message, type });
    Animated.timing(slideAnim, { toValue: insets.top + 10, duration: 300, useNativeDriver: true }).start(() => {
      setTimeout(() => {
        Animated.timing(slideAnim, { toValue: -100, duration: 300, useNativeDriver: true })
          .start(() => setToast({ visible: false, message: '', type: 'info' }));
      }, 3500);
    });
  }, [insets.top, slideAnim]);

  const fetchEmpresas = async () => {
    try {
      setLoading(true);
      const { data, error } = await supabase
        .from('empresas')
        .select('*')
        .order('curso', { ascending: true })
        .order('nome', { ascending: true });
      if (error) throw error;
      setEmpresas(data || []);
    } catch (error: any) {
      showToast('Não foi possível carregar as empresas.', 'error');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

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

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    fetchEmpresas();
  }, []);

  const secoesAgrupadas = useMemo(() => {
    const filtradas = empresas.filter(e =>
      e.nome?.toLowerCase().includes(search.toLowerCase()) ||
      e.curso?.toLowerCase().includes(search.toLowerCase())
    );

    const grupos = filtradas.reduce((acc: { [key: string]: Empresa[] }, empresa) => {
      const cursoKey = (empresa.curso || 'Geral').trim().toUpperCase();
      if (!acc[cursoKey]) acc[cursoKey] = [];
      acc[cursoKey].push(empresa);
      return acc;
    }, {});

    return Object.keys(grupos).map(cursoNome => ({
      title: cursoNome,
      data: grupos[cursoNome],
    })).sort((a, b) => a.title.localeCompare(b.title));
  }, [search, empresas]);

  return (
    <View style={{ flex: 1, backgroundColor: cores.fundo }}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} translucent backgroundColor="transparent" />

      {/* 🟢 TOAST ANIMADO NO TOPO */}
      <Animated.View style={[
        styles.toastContainer, 
        { transform: [{ translateY: slideAnim }] },
        toast.type === 'error' ? { backgroundColor: cores.vermelho } : 
        toast.type === 'success' ? { backgroundColor: cores.verde } : 
        { backgroundColor: cores.azul }
      ]}>
        <Ionicons 
          name={toast.type === 'error' ? "warning" : toast.type === 'success' ? "checkmark-circle" : "information-circle"} 
          size={24} 
          color="#FFF" 
        />
        <Text style={styles.toastText}>{toast.message}</Text>
      </Animated.View>

      <SafeAreaView style={styles.safe} edges={['top', 'left', 'right']}>
        
        {/* HEADER MODERNO */}
        <View style={styles.header}>
          <TouchableOpacity 
            style={[styles.backBtn, { borderColor: cores.borda, backgroundColor: cores.card }]} 
            onPress={() => router.back()}
          >
            <Ionicons name="chevron-back" size={24} color={cores.azul} />
          </TouchableOpacity>
          
          <View style={{ flex: 1, marginLeft: 15 }}>
            <Text style={[styles.headerTitle, { color: cores.texto }]}>Entidades</Text>
            <Text style={[styles.headerSubtitle, { color: cores.laranja }]}>
              {empresas.length} parcerias ativas
            </Text>
          </View>
        </View>

        {/* PESQUISA */}
        <View style={styles.searchSection}>
          <View style={[styles.searchBar, { backgroundColor: cores.card, borderColor: cores.borda }]}>
            <Ionicons name="search-outline" size={20} color={cores.secundario} style={{ marginRight: 10 }} />
            <TextInput
              style={[styles.searchInput, { color: cores.texto }]}
              placeholder="Procurar empresa ou curso..."
              placeholderTextColor={cores.secundario}
              value={search}
              onChangeText={setSearch}
            />
          </View>
        </View>

        {loading && !refreshing ? (
          <View style={styles.loadingCenter}>
            <ActivityIndicator size="large" color={cores.azul} />
          </View>
        ) : (
          <SectionList
            sections={secoesAgrupadas}
            keyExtractor={item => item.id.toString()}
            stickySectionHeadersEnabled={false}
            showsVerticalScrollIndicator={false}
            contentContainerStyle={[styles.listPadding, { paddingBottom: insets.bottom + 20 }]}
            refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={cores.azul} />}
            renderSectionHeader={({ section: { title } }) => (
              <View style={styles.sectionHeader}>
                <View style={[styles.sectionDot, { backgroundColor: cores.laranja }]} />
                <Text style={[styles.sectionTitle, { color: cores.texto }]}>{title}</Text>
                <View style={[styles.sectionLine, { backgroundColor: cores.borda }]} />
              </View>
            )}
            renderItem={({ item }) => (
              <TouchableOpacity
                activeOpacity={0.7}
                style={[styles.empresaCard, { backgroundColor: cores.card, borderColor: cores.borda }]}
                onPress={() => router.push({ pathname: '/Professor/Empresas/DetalhesEmpresa', params: { empresa: JSON.stringify(item) } })}
              >
                <View style={[styles.empresaIcon, { backgroundColor: cores.azulSuave }]}>
                  <Ionicons name="business-outline" size={22} color={cores.azul} />
                </View>
                
                <View style={styles.empresaInfo}>
                  <Text style={[styles.empresaNome, { color: cores.texto }]} numberOfLines={1}>{item.nome}</Text>
                  <View style={styles.tutorRow}>
                    <Ionicons name="location-outline" size={14} color={cores.secundario} />
                    <Text style={[styles.tutorText, { color: cores.secundario }]} numberOfLines={1}>{item.morada}</Text>
                  </View>
                </View>

                <View style={[styles.arrowCircle, { borderColor: cores.borda, backgroundColor: cores.fundo }]}>
                  <Ionicons name="chevron-forward" size={16} color={cores.azul} />
                </View>
              </TouchableOpacity>
            )}
            ListEmptyComponent={() => (
              <View style={styles.emptyContainer}>
                <View style={[styles.emptyIconCircle, { backgroundColor: cores.azulSuave }]}>
                  <Ionicons name="business-outline" size={40} color={cores.azul} />
                </View>
                <Text style={[styles.emptyText, { color: cores.secundario }]}>Nenhuma entidade encontrada.</Text>
              </View>
            )}
          />
        )}
      </SafeAreaView>
    </View>
  );
});

const styles = StyleSheet.create({
  safe: { flex: 1 },
  // TOAST STYLES
  toastContainer: { position: 'absolute', left: 20, right: 20, zIndex: 1000, flexDirection: 'row', alignItems: 'center', padding: 16, borderRadius: 16, elevation: 6, shadowColor: '#000', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.2, shadowRadius: 8 },
  toastText: { color: '#FFF', fontSize: 14, fontWeight: '700', marginLeft: 12, flex: 1 },

  header: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 20, paddingVertical: 15 },
  backBtn: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center', borderWidth: 1 },
  headerTitle: { fontSize: 24, fontWeight: '900', letterSpacing: -0.5 },
  headerSubtitle: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 2 },
  
  searchSection: { paddingHorizontal: 20, marginBottom: 10 },
  searchBar: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, height: 56, borderRadius: 18, borderWidth: 1.5 },
  searchInput: { flex: 1, fontSize: 15, fontWeight: '600' },
  
  loadingCenter: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  
  listPadding: { paddingHorizontal: 20 },
  sectionHeader: { flexDirection: 'row', alignItems: 'center', marginTop: 20, marginBottom: 15 },
  sectionDot: { width: 8, height: 8, borderRadius: 4, marginRight: 10 },
  sectionTitle: { fontSize: 14, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 0.5 },
  sectionLine: { flex: 1, height: 1.5, marginLeft: 15, opacity: 0.6 },
  
  empresaCard: { flexDirection: 'row', alignItems: 'center', padding: 16, borderRadius: 24, marginBottom: 12, borderWidth: 1, elevation: 2, shadowColor: '#000', shadowOpacity: 0.03, shadowRadius: 8, shadowOffset: { width: 0, height: 2 } },
  empresaIcon: { width: 48, height: 48, borderRadius: 16, justifyContent: 'center', alignItems: 'center' },
  empresaInfo: { flex: 1, marginLeft: 16, paddingRight: 10 },
  empresaNome: { fontSize: 16, fontWeight: '800', letterSpacing: -0.3, marginBottom: 4 },
  tutorRow: { flexDirection: 'row', alignItems: 'center', gap: 6 },
  tutorText: { fontSize: 13, fontWeight: '600' },
  arrowCircle: { width: 34, height: 34, borderRadius: 12, borderWidth: 1, justifyContent: 'center', alignItems: 'center' },
  
  emptyContainer: { marginTop: 100, alignItems: 'center' },
  emptyIconCircle: { width: 80, height: 80, borderRadius: 40, justifyContent: 'center', alignItems: 'center', marginBottom: 15 },
  emptyText: { fontSize: 15, fontWeight: '700' }
});

export default ListaEmpresasProfessor;