import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { useFocusEffect } from '@react-navigation/native';
import React, { useCallback, useState } from 'react';
import { Alert, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { SyncStatusBar } from '../components/SyncStatusBar';
import { getOutboxCounts, OutboxCounts } from '../db/outbox';
import { isOnline } from '../net/connectivity';
import { runSync } from '../sync/engine';
import { useAutoSync } from '../sync/useAutoSync';
import { RootStackParamList } from '../navigation/types';
import { COLORS, PrimaryButton } from '../ui/components';
import { PhasesSection } from './sections/PhasesSection';
import { FeaturesSection } from './sections/FeaturesSection';
import { IssuesSection } from './sections/IssuesSection';

type Props = NativeStackScreenProps<RootStackParamList, 'ProjectDetail'>;

const EMPTY: OutboxCounts = { pending: 0, conflict: 0, error: 0, mediaPending: 0 };
const TABS = ['Fases', 'Features', 'Incidencias'] as const;
type Tab = (typeof TABS)[number];

export function ProjectDetailScreen({ route, navigation }: Props) {
  const { projectId } = route.params;
  const [tab, setTab] = useState<Tab>('Fases');
  const [counts, setCounts] = useState<OutboxCounts>(EMPTY);
  const [syncing, setSyncing] = useState(false);
  // Se incrementa tras cada sync para forzar el recargado de la sección visible.
  const [nonce, setNonce] = useState(0);

  const refreshCounts = useCallback(() => {
    void getOutboxCounts().then(setCounts);
  }, []);

  useFocusEffect(refreshCounts);

  /** Ciclo de sync; refresca contadores y la sección visible. */
  const doSync = useCallback(async () => {
    setSyncing(true);
    try {
      return await runSync(projectId);
    } finally {
      refreshCounts();
      setNonce((n) => n + 1);
      setSyncing(false);
    }
  }, [projectId, refreshCounts]);

  // Auto-sync (silencioso) al recuperar red / volver a primer plano / por intervalo.
  useAutoSync(true, async () => {
    await doSync();
  });

  // Sync manual (con resumen).
  const onSync = useCallback(async () => {
    if (!(await isOnline())) {
      Alert.alert('Sin conexión', 'Conéctate para sincronizar.');
      return;
    }
    try {
      const report = await doSync();
      Alert.alert(
        'Sincronización completada',
        `Enviadas: ${report.applied}/${report.pushed}\n` +
          `Conflictos: ${report.conflicts} · Errores: ${report.errors}\n` +
          `Fotos: ${report.mediaUploaded} (errores ${report.mediaErrors})`,
      );
    } catch (e) {
      Alert.alert('Error de sincronización', e instanceof Error ? e.message : String(e));
    }
  }, [doSync]);

  return (
    <View style={styles.container}>
      <SyncStatusBar
        counts={counts}
        syncing={syncing}
        onPress={() => navigation.navigate('Outbox')}
      />

      <View style={styles.tabs}>
        {TABS.map((t) => (
          <TouchableOpacity
            key={t}
            style={[styles.tab, tab === t && styles.tabActive]}
            onPress={() => setTab(t)}
          >
            <Text style={[styles.tabText, tab === t && styles.tabTextActive]}>{t}</Text>
          </TouchableOpacity>
        ))}
      </View>

      <View style={styles.content} key={`${tab}-${nonce}`}>
        {tab === 'Fases' && <PhasesSection projectId={projectId} />}
        {tab === 'Features' && <FeaturesSection projectId={projectId} />}
        {tab === 'Incidencias' && <IssuesSection projectId={projectId} />}
      </View>

      <View style={styles.footer}>
        <PrimaryButton
          title={syncing ? 'Sincronizando…' : 'Sincronizar'}
          onPress={() => void onSync()}
          loading={syncing}
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  tabs: { flexDirection: 'row', borderBottomWidth: StyleSheet.hairlineWidth, borderColor: COLORS.border },
  tab: { flex: 1, paddingVertical: 12, alignItems: 'center' },
  tabActive: { borderBottomWidth: 2, borderColor: COLORS.primary },
  tabText: { fontSize: 14, color: COLORS.muted },
  tabTextActive: { color: COLORS.primary, fontWeight: '700' },
  content: { flex: 1 },
  footer: { padding: 12, borderTopWidth: StyleSheet.hairlineWidth, borderColor: COLORS.border },
});
