import { NativeStackScreenProps } from '@react-navigation/native-stack';
import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import {
  ActivityIndicator,
  FlatList,
  RefreshControl,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import * as api from '../api/endpoints';
import { Project } from '../api/types';
import { useSession } from '../auth/session';
import { getProjects, saveProjectList, saveTemplates, setActiveProjectId } from '../db/repositories';
import { isOnline } from '../net/connectivity';
import { runSync } from '../sync/engine';
import { RootStackParamList } from '../navigation/types';
import { COLORS } from '../ui/components';

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

/** Tolerante con la forma de la respuesta: `{projects}` (actual), `{data}` o array. */
function normalize(res: unknown): Project[] {
  if (Array.isArray(res)) return res as Project[];
  const obj = (res ?? {}) as { projects?: Project[]; data?: Project[] };
  return obj.projects ?? obj.data ?? [];
}

export function ProjectsScreen({ navigation }: Props) {
  const { user, signOut } = useSession();
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(false);
  const [opening, setOpening] = useState<number | null>(null);
  const [showMenu, setShowMenu] = useState(false);

  // Mueve el menú de usuario al header nativo
  useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <View style={styles.headerRight}>
          <TouchableOpacity
            onPress={() => setShowMenu(!showMenu)}
            activeOpacity={0.7}
            style={styles.userButton}
          >
            <Text style={styles.dropdownLabel}>
              {user?.name?.split(' ')[0] ?? 'Usuario'}
              <Text style={styles.chevronSmall}> ▼</Text>
            </Text>
          </TouchableOpacity>
        </View>
      ),
    });
  }, [navigation, user, showMenu]);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      if (await isOnline()) {
        const list = normalize(await api.listProjects());
        await saveProjectList(list);
        try {
          const { templates } = await api.getTemplates();
          await saveTemplates(templates);
        } catch (e) {
          console.warn('No se pudieron prefetchar las plantillas:', e);
        }
      }
      setProjects(await getProjects());
    } catch (e) {
      console.warn('No se pudo refrescar /projects, usando datos locales:', e);
      setProjects(await getProjects()); // fallback offline
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  const openProject = useCallback(
    async (p: Project) => {
      setOpening(p.id);
      try {
        await setActiveProjectId(p.id);
        if (await isOnline()) await runSync(p.id);
        navigation.navigate('ProjectDetail', { projectId: p.id, name: p.name });
      } finally {
        setOpening(null);
      }
    },
    [navigation],
  );

  const handleLogout = () => {
    setShowMenu(false);
    signOut();
  };

  const handleSettings = () => {
    setShowMenu(false);
    navigation.navigate('Settings');
  };

  return (
    <View style={styles.container}>
      {/* Menu flotante (se posiciona relativo al contenedor principal) */}
      {showMenu && (
        <View style={styles.floatingMenu}>
          <TouchableOpacity style={styles.dropdownItem} onPress={handleSettings} activeOpacity={0.7}>
            <Text style={styles.dropdownItemText}>⚙ Configuración</Text>
          </TouchableOpacity>
          <TouchableOpacity style={[styles.dropdownItem, styles.dropdownItemDanger]} onPress={handleLogout} activeOpacity={0.7}>
            <Text style={styles.dropdownItemText}>Salir</Text>
          </TouchableOpacity>
        </View>
      )}

      {/* Close dropdown when tapping outside */}
      <TouchableOpacity
        onPress={() => setShowMenu(false)}
        style={styles.touchOutside}
        activeOpacity={1}
      >
        <FlatList
          data={projects}
          keyExtractor={(p) => String(p.id)}
          refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
          ListEmptyComponent={loading ? null : <Text style={styles.empty}>No hay proyectos.</Text>}
          renderItem={({ item }) => (
            <TouchableOpacity style={styles.card} onPress={() => openProject(item)} activeOpacity={0.7}>
              <View style={styles.cardContent}>
                <Text style={styles.cardName}>{item.name}</Text>
                {item.reference ? <Text style={styles.cardMeta}>Ref: {item.reference}</Text> : null}
                {item.address ? <Text style={styles.cardMeta}>📍 {item.address}</Text> : null}
                {item.status ? <Text style={styles.cardMeta}>Estado: {item.status}</Text> : null}
              </View>
              {opening === item.id ? (
                <ActivityIndicator />
              ) : (
                <Text style={styles.chevron}>›</Text>
              )}
            </TouchableOpacity>
          )}
        />
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#fff' },
  headerRight: {
    marginRight: 8,
  },
  userButton: {
    paddingHorizontal: 8,
    paddingVertical: 4,
  },
  dropdownLabel: {
    fontSize: 15,
    fontWeight: '600',
    color: COLORS.primary,
  },
  chevronSmall: { fontSize: 10, color: COLORS.primary },
  floatingMenu: {
    position: 'absolute',
    top: 4,
    right: 16,
    backgroundColor: '#fff',
    borderRadius: 8,
    borderWidth: 1,
    borderColor: COLORS.border,
    overflow: 'hidden',
    minWidth: 180,
    elevation: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.2,
    shadowRadius: 5,
    zIndex: 1000,
  },
  dropdownItem: {
    paddingHorizontal: 16,
    paddingVertical: 14,
  },
  dropdownItemDanger: {
    borderTopWidth: StyleSheet.hairlineWidth,
    borderTopColor: COLORS.border,
  },
  dropdownItemText: {
    fontSize: 15,
    color: '#333',
  },
  touchOutside: {
    flex: 1,
  },
  card: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 18,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderColor: COLORS.border,
    backgroundColor: '#fff',
  },
  cardContent: { flex: 1 },
  cardName: { fontSize: 16, fontWeight: '700', color: '#111' },
  cardMeta: { fontSize: 13, color: COLORS.muted, marginTop: 4 },
  chevron: { fontSize: 20, color: COLORS.border, marginLeft: 8 },
  empty: { textAlign: 'center', marginTop: 40, color: '#888' },
});

