// app/Professor/Empresas/DetalhesEmpresa.tsx
import { Ionicons } from '@expo/vector-icons';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { memo, useEffect, useMemo, useState } from 'react';
import {
  ActivityIndicator,
  KeyboardAvoidingView,
  Modal,
  Platform,
  ScrollView,
  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: string;
  nome: string;
  morada: string;
  tutor_nome: string;
  tutor_telefone: string;
  curso: string;
}

const DetalhesEmpresa = memo(() => {
  const { isDarkMode } = useTheme();
  const router = useRouter();
  const params = useLocalSearchParams();
  const insets = useSafeAreaInsets();

  const azulEPVC = '#2390a6';
  const laranjaEPVC = '#E38E00';

  const empresaOriginal: Empresa = useMemo(() => {
    if (!params.empresa) return {} as Empresa;
    const str = Array.isArray(params.empresa) ? params.empresa[0] : params.empresa;
    try {
      return JSON.parse(str);
    } catch {
      return {} as Empresa;
    }
  }, [params.empresa]);

  const [empresaLocal, setEmpresaLocal] = useState<Empresa>({ ...empresaOriginal });
  const [alunos, setAlunos] = useState<{ id: string; nome: string }[]>([]);
  const [loadingAlunos, setLoadingAlunos] = useState(true);
  const [editando, setEditando] = useState(false);
  const [loading, setLoading] = useState(false);
  const [showSuccess, setShowSuccess] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);

  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',
    vermelho: '#EF4444',
    vermelhoSuave: '#FFF5F5',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
    overlay: 'rgba(26, 54, 93, 0.8)',
  }), [isDarkMode]);

  useEffect(() => {
    if (empresaLocal.id) carregarAlunos();
  }, [empresaLocal.id]);

  async function carregarAlunos() {
    try {
      setLoadingAlunos(true);
      const { data: estagios } = await supabase.from('estagios').select('aluno_id').eq('empresa_id', empresaLocal.id);
      if (!estagios || estagios.length === 0) { setAlunos([]); return; }
      
      const ids = estagios.map(e => e.aluno_id).filter(id => id !== null);
      const { data: listaAlunos } = await supabase.from('alunos').select('id, nome').in('id', ids);
      setAlunos(listaAlunos || []);
    } catch (error) {
      setAlunos([]);
    } finally {
      setLoadingAlunos(false);
    }
  }

  const handleSave = async () => {
    try {
      setLoading(true);
      const { error } = await supabase.from('empresas').update({
        nome: empresaLocal.nome,
        morada: empresaLocal.morada,
        tutor_nome: empresaLocal.tutor_nome,
        tutor_telefone: empresaLocal.tutor_telefone,
        curso: empresaLocal.curso,
      }).eq('id', empresaLocal.id);

      if (error) throw error;
      
      setEditando(false);
      setShowSuccess(true);
      setTimeout(() => setShowSuccess(false), 3000);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const confirmDelete = async () => {
    try {
      setLoading(true);
      const { error } = await supabase.from('empresas').delete().eq('id', empresaLocal.id);
      if (error) throw error;
      setShowDeleteModal(false);
      router.back();
    } catch (e) {
      setShowDeleteModal(false);
      alert('Não é possível apagar empresas com estágios ativos.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={{ flex: 1, backgroundColor: cores.fundo }}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
      
      {showSuccess && (
        <View style={[styles.toast, { backgroundColor: cores.azul, top: insets.top + 10 }]}>
          <Ionicons name="checkmark-circle" size={20} color="#fff" />
          <Text style={styles.toastText}>Dados atualizados!</Text>
        </View>
      )}

      <Modal visible={showDeleteModal} transparent animationType="fade">
        <View style={[styles.modalOverlay, { backgroundColor: cores.overlay }]}>
          <View style={[styles.modalContent, { backgroundColor: cores.card, borderColor: cores.borda }]}>
            <View style={[styles.iconCircle, { backgroundColor: cores.vermelhoSuave }]}>
              <Ionicons name="warning" size={35} color={cores.vermelho} />
            </View>
            <Text style={[styles.modalTitle, { color: cores.texto }]}>Eliminar Entidade?</Text>
            <Text style={[styles.modalSubtitle, { color: cores.secundario }]}>
              Esta ação é irreversível. A empresa <Text style={{fontWeight: '900', color: cores.texto}}>{empresaLocal.nome}</Text> será removida do sistema.
            </Text>
            
            <View style={styles.modalButtons}>
              <TouchableOpacity 
                style={[styles.modalBtn, { backgroundColor: isDarkMode ? '#2D2D2D' : '#E2E8F0' }]} 
                onPress={() => setShowDeleteModal(false)}
              >
                <Text style={[styles.modalBtnTxt, { color: cores.texto }]}>Cancelar</Text>
              </TouchableOpacity>
              
              <TouchableOpacity 
                style={[styles.modalBtn, { backgroundColor: cores.vermelho }]} 
                onPress={confirmDelete}
              >
                {loading ? <ActivityIndicator color="#fff" /> : <Text style={[styles.modalBtnTxt, { color: '#fff' }]}>Confirmar</Text>}
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>

      <SafeAreaView style={styles.safe} edges={['top']}>
        <View style={styles.header}>
          <TouchableOpacity 
            style={[styles.btnAction, { borderColor: cores.borda }]} 
            onPress={() => router.back()}
          >
            <Ionicons name="chevron-back" size={24} color={cores.azul} />
          </TouchableOpacity>

          <View style={{alignItems: 'center'}}>
            <Text style={[styles.headerTitle, { color: cores.texto }]}>Ficha Técnica</Text>
            <Text style={[styles.headerSubtitle, { color: cores.laranja }]}>ID: #{empresaLocal.id?.slice(0, 5)}</Text>
          </View>

          <TouchableOpacity 
            style={[styles.btnAction, { backgroundColor: editando ? cores.laranja : 'transparent', borderColor: editando ? cores.laranja : cores.borda }]} 
            onPress={() => {
                if(editando) setEmpresaLocal({...empresaOriginal});
                setEditando(!editando);
            }}
          >
            <Ionicons name={editando ? "close" : "create-outline"} size={22} color={editando ? "#fff" : cores.azul} />
          </TouchableOpacity>
        </View>

        <ScrollView contentContainerStyle={[styles.scroll, { paddingBottom: insets.bottom + 30 }]} showsVerticalScrollIndicator={false}>
          
          <View style={[styles.card, { backgroundColor: cores.card, borderColor: cores.borda }]}>
             <View style={styles.sectionHeader}>
                <View style={[styles.sideLine, { backgroundColor: cores.azul }]} />
                <Text style={[styles.sectionTitle, { color: cores.texto }]}>Informação Institucional</Text>
             </View>
             <ModernField label="Nome da Entidade" value={empresaLocal.nome} editable={editando} onChangeText={(v: string) => setEmpresaLocal(p => ({...p, nome: v}))} cores={cores} icon="business-outline" />
             <ModernField label="Curso Associado" value={empresaLocal.curso} editable={editando} onChangeText={(v: string) => setEmpresaLocal(p => ({...p, curso: v}))} cores={cores} icon="school-outline" />
             <ModernField label="Endereço Completo" value={empresaLocal.morada} editable={editando} onChangeText={(v: string) => setEmpresaLocal(p => ({...p, morada: v}))} cores={cores} multiline icon="map-outline" />
          </View>

          <View style={[styles.card, { backgroundColor: cores.card, borderColor: cores.borda }]}>
             <View style={styles.sectionHeader}>
                <View style={[styles.sideLine, { backgroundColor: cores.laranja }]} />
                <Text style={[styles.sectionTitle, { color: cores.texto }]}>Gestão de Contacto</Text>
             </View>
             <ModernField label="Tutor Responsável" value={empresaLocal.tutor_nome} editable={editando} onChangeText={(v: string) => setEmpresaLocal(p => ({...p, tutor_nome: v}))} cores={cores} icon="person-outline" />
             <ModernField label="Contacto Telefónico" value={empresaLocal.tutor_telefone} editable={editando} onChangeText={(v: string) => setEmpresaLocal(p => ({...p, tutor_telefone: v}))} cores={cores} keyboardType="phone-pad" icon="call-outline" />
          </View>

          <View style={[styles.card, { backgroundColor: cores.card, borderColor: cores.borda }]}>
            <View style={styles.sectionHeader}>
                <View style={[styles.sideLine, { backgroundColor: cores.secundario }]} />
                <Text style={[styles.sectionTitle, { color: cores.texto }]}>Alunos em Estágio</Text>
                <View style={[styles.countBadge, { backgroundColor: cores.azul }]}>
                    <Text style={styles.countBadgeTxt}>{loadingAlunos ? '-' : alunos.length}</Text>
                </View>
            </View>
            {loadingAlunos ? <ActivityIndicator size="small" color={cores.azul} /> : alunos.length > 0 ? (
              alunos.map((aluno, i) => (
                <View key={aluno.id} style={[styles.alunoRow, i !== alunos.length - 1 && { borderBottomWidth: 1, borderBottomColor: cores.borda }]}>
                  <View style={[styles.miniAvatar, { backgroundColor: cores.azulSuave }]}>
                    <Ionicons name="person" size={14} color={cores.azul} />
                  </View>
                  <Text style={[styles.alunoName, { color: cores.texto }]}>{aluno.nome}</Text>
                  <Ionicons name="chevron-forward" size={14} color={cores.secundario} opacity={0.3} />
                </View>
              ))
            ) : <Text style={[styles.empty, { color: cores.secundario }]}>Nenhum aluno vinculado a esta entidade.</Text>}
          </View>

          <View style={styles.footerActions}>
            {editando ? (
              <TouchableOpacity style={[styles.btnSave, { backgroundColor: cores.azul }]} onPress={handleSave} disabled={loading}>
                {loading ? <ActivityIndicator color="#fff" /> : (
                  <View style={styles.btnRow}>
                    <Ionicons name="save-outline" size={20} color="#fff" />
                    <Text style={styles.btnSaveTxt}>Confirmar Alterações</Text>
                  </View>
                )}
              </TouchableOpacity>
            ) : (
              <TouchableOpacity style={[styles.btnDel, { borderColor: cores.vermelho }]} onPress={() => setShowDeleteModal(true)}>
                <Ionicons name="trash-bin-outline" size={18} color={cores.vermelho} />
                <Text style={[styles.btnDelTxt, { color: cores.vermelho }]}>Remover Parceiro</Text>
              </TouchableOpacity>
            )}
          </View>
        </ScrollView>
      </SafeAreaView>
    </KeyboardAvoidingView>
  );
});

const ModernField = ({ label, value, editable, cores, icon, ...props }: any) => (
  <View style={styles.fieldContainer}>
    <View style={styles.labelRow}>
        <Ionicons name={icon} size={12} color={cores.secundario} />
        <Text style={[styles.fieldLabel, { color: cores.secundario }]}>{label}</Text>
    </View>
    {editable ? (
      <TextInput 
        style={[styles.input, { color: cores.texto, backgroundColor: cores.fundo, borderColor: cores.azul }]} 
        value={value} 
        selectionColor={cores.laranja} 
        {...props} 
      />
    ) : (
      <View style={[styles.readOnly, { backgroundColor: cores.fundo, borderColor: cores.borda }]}>
        <Text style={[styles.readOnlyTxt, { color: cores.texto }]}>{value || 'Não definido'}</Text>
      </View>
    )}
  </View>
);

const styles = StyleSheet.create({
  safe: { flex: 1 },
  toast: { position: 'absolute', left: 25, right: 25, zIndex: 999, flexDirection: 'row', alignItems: 'center', padding: 18, borderRadius: 20, gap: 12, elevation: 8 },
  toastText: { color: '#fff', fontSize: 14, fontWeight: '900' },
  header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 24, paddingVertical: 15 },
  headerTitle: { fontSize: 20, fontWeight: '900', letterSpacing: -0.5 },
  headerSubtitle: { fontSize: 10, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 1 },
  btnAction: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center', borderWidth: 1 },
  scroll: { paddingHorizontal: 24, paddingTop: 10 },
  card: { padding: 22, borderRadius: 32, borderWidth: 1, marginBottom: 18, elevation: 2, shadowColor: '#000', shadowOpacity: 0.02, shadowRadius: 10 },
  sectionHeader: { flexDirection: 'row', alignItems: 'center', marginBottom: 20, gap: 10 },
  sideLine: { width: 4, height: 18, borderRadius: 2 },
  sectionTitle: { fontSize: 13, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 0.5 },
  fieldContainer: { marginBottom: 18 },
  labelRow: { flexDirection: 'row', alignItems: 'center', gap: 6, marginBottom: 6, marginLeft: 4 },
  fieldLabel: { fontSize: 10, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 0.5 },
  input: { fontSize: 15, fontWeight: '700', paddingHorizontal: 16, paddingVertical: 12, borderRadius: 16, borderWidth: 1.5 },
  readOnly: { paddingHorizontal: 16, paddingVertical: 14, borderRadius: 16, borderWidth: 1 },
  readOnlyTxt: { fontSize: 15, fontWeight: '700' },
  countBadge: { width: 22, height: 22, borderRadius: 11, justifyContent: 'center', alignItems: 'center' },
  countBadgeTxt: { color: '#fff', fontSize: 11, fontWeight: '900' },
  alunoRow: { flexDirection: 'row', alignItems: 'center', paddingVertical: 14 },
  miniAvatar: { width: 32, height: 32, borderRadius: 10, justifyContent: 'center', alignItems: 'center', marginRight: 12 },
  alunoName: { fontSize: 15, fontWeight: '700', flex: 1 },
  empty: { textAlign: 'center', fontSize: 13, fontWeight: '600', paddingVertical: 10, fontStyle: 'italic' },
  footerActions: { marginTop: 10 },
  btnSave: { height: 60, borderRadius: 22, justifyContent: 'center', alignItems: 'center', elevation: 5, shadowColor: '#2390a6', shadowOpacity: 0.3, shadowRadius: 10 },
  btnRow: { flexDirection: 'row', alignItems: 'center', gap: 10 },
  btnSaveTxt: { color: '#fff', fontSize: 16, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 1 },
  btnDel: { height: 56, borderRadius: 20, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', gap: 8, borderWidth: 1.5, borderStyle: 'dashed' },
  btnDelTxt: { fontSize: 14, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 0.5 },
  modalOverlay: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 25 },
  modalContent: { width: '100%', borderRadius: 40, padding: 30, alignItems: 'center', borderWidth: 1 },
  iconCircle: { width: 80, height: 80, borderRadius: 40, justifyContent: 'center', alignItems: 'center', marginBottom: 20 },
  modalTitle: { fontSize: 24, fontWeight: '900', marginBottom: 12 },
  modalSubtitle: { fontSize: 15, textAlign: 'center', lineHeight: 22, marginBottom: 30 },
  modalButtons: { flexDirection: 'row', gap: 15 },
  modalBtn: { flex: 1, height: 55, borderRadius: 18, justifyContent: 'center', alignItems: 'center' },
  modalBtnTxt: { fontSize: 15, fontWeight: '900' }
});

export default DetalhesEmpresa;