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

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);
  const [modalVisible, setModalVisible] = useState(false);

  const [form, setForm] = useState({ nome: '', morada: '', tutorNome: '', tutorTelefone: '', curso: '' });

  // Cores EPVC
  const azulEPVC = '#2390a6';
  const laranjaEPVC = '#E38E00';

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0A0A0A' : '#FFFFFF',
    card: isDarkMode ? '#161618' : '#F8FAFC',
    texto: isDarkMode ? '#F8FAFC' : '#1A365D',
    secundario: isDarkMode ? '#94A3B8' : '#718096',
    azul: azulEPVC,
    laranja: laranjaEPVC,
    azulSuave: isDarkMode ? 'rgba(35, 144, 166, 0.15)' : '#F0F9FA',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
  }), [isDarkMode]);

  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) {
      Alert.alert('Erro', 'Não foi possível carregar as empresas.');
    } 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]);

  const criarEmpresa = async () => {
    if (!form.nome || !form.morada || !form.tutorNome || !form.tutorTelefone || !form.curso) {
      Alert.alert('Atenção', 'Preencha todos os campos.');
      return;
    }

    try {
      setLoading(true);
      const { data, error } = await supabase
        .from('empresas')
        .insert([{
          nome: form.nome.trim(),
          morada: form.morada.trim(),
          tutor_nome: form.tutorNome.trim(),
          tutor_telefone: form.tutorTelefone.trim(),
          curso: form.curso.trim().toUpperCase(),
        }])
        .select();

      if (error) throw error;
      setEmpresas(prev => [...prev, data![0]]);
      setModalVisible(false);
      setForm({ nome: '', morada: '', tutorNome: '', tutorTelefone: '', curso: '' });
      Alert.alert('Sucesso', 'Empresa registada com sucesso!');
    } catch (error: any) {
      Alert.alert('Erro', error.message);
    } finally {
      setLoading(false);
    }
  };

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

      <SafeAreaView style={styles.safe} edges={['top']}>
        
        {/* HEADER EPVC */}
        <View style={styles.header}>
          <TouchableOpacity 
            style={[styles.backBtn, { borderColor: cores.borda }]} 
            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>

          <TouchableOpacity 
            style={[styles.addBtn, { backgroundColor: cores.laranja }]} 
            onPress={() => setModalVisible(true)}
          >
            <Ionicons name="add" size={30} color="#fff" />
          </TouchableOpacity>
        </View>

        {/* PESQUISA */}
        <View style={styles.searchSection}>
          <View style={[styles.searchBar, { backgroundColor: cores.card, borderColor: cores.borda }]}>
            <Ionicons name="search-outline" size={20} color={cores.azul} />
            <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}
            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.8}
                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={24} color={cores.azul} />
                </View>
                
                <View style={styles.empresaInfo}>
                  <Text style={[styles.empresaNome, { color: cores.texto }]}>{item.nome}</Text>
                  <View style={styles.tutorRow}>
                    <Ionicons name="location-outline" size={12} color={cores.secundario} />
                    <Text style={[styles.tutorText, { color: cores.secundario }]} numberOfLines={1}>{item.morada}</Text>
                  </View>
                </View>

                <View style={[styles.arrowCircle, { borderColor: cores.borda }]}>
                  <Ionicons name="chevron-forward" size={14} color={cores.azul} />
                </View>
              </TouchableOpacity>
            )}
            ListEmptyComponent={() => (
              <View style={styles.emptyContainer}>
                <Ionicons name="search-outline" size={60} color={cores.borda} />
                <Text style={{ color: cores.secundario, marginTop: 15, fontWeight: '700' }}>Nenhuma entidade encontrada.</Text>
              </View>
            )}
          />
        )}
      </SafeAreaView>

      {/* MODAL NOVO REGISTO */}
      <Modal visible={modalVisible} animationType="slide" transparent>
        <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={styles.modalOverlay}>
          <View style={[styles.modalContent, { backgroundColor: cores.card }]}>
            <View style={styles.modalHeader}>
              <View>
                <Text style={[styles.modalTitle, { color: cores.texto }]}>Registar Parceiro</Text>
                <Text style={[styles.modalSub, { color: cores.laranja }]}>Nova entidade de estágio</Text>
              </View>
              <TouchableOpacity onPress={() => setModalVisible(false)} style={styles.closeBtn}>
                <Ionicons name="close" size={24} color={cores.texto} />
              </TouchableOpacity>
            </View>

            <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={{ paddingBottom: 30 }}>
              <ModernInput label="Nome da Empresa" icon="business" value={form.nome} onChangeText={(v:any)=>setForm({...form, nome:v})} cores={cores} />
              <ModernInput label="Curso Associado" icon="school" value={form.curso} onChangeText={(v:any)=>setForm({...form, curso:v})} cores={cores} placeholder="Ex: GPSI, MULT, etc." />
              <ModernInput label="Localização / Morada" icon="map" value={form.morada} onChangeText={(v:any)=>setForm({...form, morada:v})} cores={cores} />
              
              <View style={[styles.divider, { backgroundColor: cores.borda }]} />
              
              <ModernInput label="Tutor na Empresa" icon="person" value={form.tutorNome} onChangeText={(v:any)=>setForm({...form, tutorNome:v})} cores={cores} />
              <ModernInput label="Contacto do Tutor" icon="call" value={form.tutorTelefone} onChangeText={(v:any)=>setForm({...form, tutorTelefone:v})} keyboardType="phone-pad" cores={cores} />
              
              <TouchableOpacity style={[styles.saveBtn, { backgroundColor: cores.azul }]} onPress={criarEmpresa}>
                <Text style={styles.saveBtnText}>Confirmar Registo</Text>
              </TouchableOpacity>
            </ScrollView>
          </View>
        </KeyboardAvoidingView>
      </Modal>
    </View>
  );
});

const ModernInput = ({ label, icon, cores, ...props }: any) => (
  <View style={styles.inputWrapper}>
    <Text style={[styles.inputLabel, { color: cores.secundario }]}>{label}</Text>
    <View style={[styles.inputContainer, { backgroundColor: cores.fundo, borderColor: cores.borda }]}>
      <Ionicons name={icon} size={18} color={cores.azul} style={{ marginRight: 12 }} />
      <TextInput {...props} style={[styles.textInput, { color: cores.texto }]} placeholderTextColor={cores.secundario} />
    </View>
  </View>
);

const styles = StyleSheet.create({
  safe: { flex: 1 },
  header: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 24, paddingVertical: 15 },
  backBtn: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center', borderWidth: 1 },
  headerTitle: { fontSize: 26, fontWeight: '900', letterSpacing: -0.8 },
  headerSubtitle: { fontSize: 12, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 0.5 },
  addBtn: { width: 48, height: 48, borderRadius: 16, justifyContent: 'center', alignItems: 'center', elevation: 4, shadowColor: '#E38E00', shadowOpacity: 0.3, shadowRadius: 8 },
  searchSection: { paddingHorizontal: 24, marginVertical: 15 },
  searchBar: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, height: 56, borderRadius: 20, borderWidth: 1.5 },
  searchInput: { flex: 1, marginLeft: 10, fontSize: 15, fontWeight: '700' },
  loadingCenter: { marginTop: 60, alignItems: 'center' },
  emptyContainer: { marginTop: 100, alignItems: 'center' },
  listPadding: { paddingHorizontal: 24 },
  sectionHeader: { flexDirection: 'row', alignItems: 'center', marginTop: 30, marginBottom: 15 },
  sectionDot: { width: 8, height: 8, borderRadius: 4, marginRight: 10 },
  sectionTitle: { fontSize: 14, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 1 },
  sectionLine: { flex: 1, height: 1, marginLeft: 15, opacity: 0.5 },
  empresaCard: { flexDirection: 'row', alignItems: 'center', padding: 18, borderRadius: 28, marginBottom: 14, borderWidth: 1, elevation: 3, shadowColor: '#000', shadowOpacity: 0.04, shadowRadius: 12 },
  empresaIcon: { width: 50, height: 50, borderRadius: 16, justifyContent: 'center', alignItems: 'center' },
  empresaInfo: { flex: 1, marginLeft: 15 },
  empresaNome: { fontSize: 17, fontWeight: '800', letterSpacing: -0.3 },
  tutorRow: { flexDirection: 'row', alignItems: 'center', gap: 6, marginTop: 4 },
  tutorText: { fontSize: 12, fontWeight: '600' },
  arrowCircle: { width: 28, height: 28, borderRadius: 14, borderWidth: 1, justifyContent: 'center', alignItems: 'center' },
  modalOverlay: { flex: 1, backgroundColor: 'rgba(26, 54, 93, 0.8)', justifyContent: 'flex-end' },
  modalContent: { borderTopLeftRadius: 40, borderTopRightRadius: 40, padding: 28, maxHeight: '90%' },
  modalHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 30 },
  modalTitle: { fontSize: 24, fontWeight: '900', letterSpacing: -0.5 },
  modalSub: { fontSize: 12, fontWeight: '800', textTransform: 'uppercase', marginTop: 4 },
  closeBtn: { width: 40, height: 40, borderRadius: 20, backgroundColor: 'rgba(0,0,0,0.05)', justifyContent: 'center', alignItems: 'center' },
  divider: { height: 1, marginVertical: 20, opacity: 0.5 },
  inputWrapper: { marginBottom: 20 },
  inputLabel: { fontSize: 10, fontWeight: '900', textTransform: 'uppercase', marginBottom: 8, marginLeft: 4, letterSpacing: 0.5 },
  inputContainer: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, height: 58, borderRadius: 18, borderWidth: 1.5 },
  textInput: { flex: 1, fontSize: 15, fontWeight: '700' },
  saveBtn: { height: 60, borderRadius: 22, justifyContent: 'center', alignItems: 'center', marginTop: 25, elevation: 6, shadowColor: '#2390a6', shadowOpacity: 0.3, shadowRadius: 10 },
  saveBtnText: { color: '#fff', fontSize: 16, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 1.2 }
});

export default ListaEmpresasProfessor;