/**
 * Sección Features: maestro-detalle con conmutador Lista/Mapa en el panel
 * maestro. Lista o mapa a la izquierda, detalle a la derecha (tablet) o
 * navegación a pantalla (móvil).
 */
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import React, { useCallback, useState } from 'react';
import { FlatList, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { Feature } from '../../api/types';
import { getFeatures } from '../../db/repositories';
import { RootStackParamList } from '../../navigation/types';
import { Badge, COLORS, EmptyState } from '../../ui/components';
import { FeatureMap } from '../../ui/FeatureMap';
import { MasterDetail } from '../../ui/MasterDetail';
import { FeatureDetailContent } from '../detail/FeatureDetailContent';

type Nav = NativeStackNavigationProp<RootStackParamList>;
type ViewMode = 'list' | 'map';

export function FeaturesSection({ projectId }: { projectId: number }) {
  const navigation = useNavigation<Nav>();
  const [features, setFeatures] = useState<Feature[]>([]);
  const [mode, setMode] = useState<ViewMode>('list');

  const load = useCallback(() => {
    void getFeatures(projectId).then(setFeatures);
  }, [projectId]);

  useFocusEffect(load);

  const goPhone = (id: number) => {
    const f = features.find((x) => x.id === id);
    navigation.navigate('FeatureDetail', { featureId: id, name: f?.name ?? 'Feature' });
  };

  return (
    <MasterDetail
      onSelectPhone={goPhone}
      renderDetail={(id) => <FeatureDetailContent featureId={id} />}
      renderMaster={({ selectedId, onSelect }) => (
        <View style={{ flex: 1 }}>
          <View style={styles.toggle}>
            {(['list', 'map'] as ViewMode[]).map((m) => (
              <TouchableOpacity
                key={m}
                style={[styles.toggleBtn, mode === m && styles.toggleActive]}
                onPress={() => setMode(m)}
              >
                <Text style={[styles.toggleText, mode === m && styles.toggleTextActive]}>
                  {m === 'list' ? 'Lista' : 'Mapa'}
                </Text>
              </TouchableOpacity>
            ))}
          </View>

          {features.length === 0 ? (
            <EmptyState text="Sin features." />
          ) : mode === 'map' ? (
            <FeatureMap features={features} selectedId={selectedId} onSelect={onSelect} />
          ) : (
            <FlatList
              data={features}
              keyExtractor={(f) => String(f.id)}
              renderItem={({ item }) => (
                <TouchableOpacity
                  style={[styles.row, item.id === selectedId && styles.rowActive]}
                  onPress={() => onSelect(item.id)}
                >
                  <View style={{ flex: 1 }}>
                    <Text style={styles.name}>{item.name}</Text>
                    {item.status ? <Text style={styles.meta}>{item.status}</Text> : null}
                  </View>
                  <Badge label={`${Math.round(item.progress ?? 0)}%`} color={COLORS.muted} />
                </TouchableOpacity>
              )}
            />
          )}
        </View>
      )}
    />
  );
}

const styles = StyleSheet.create({
  toggle: {
    flexDirection: 'row',
    padding: 8,
    gap: 8,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderColor: COLORS.border,
  },
  toggleBtn: {
    paddingHorizontal: 14,
    paddingVertical: 6,
    borderRadius: 16,
    borderWidth: 1,
    borderColor: COLORS.border,
  },
  toggleActive: { backgroundColor: COLORS.primary, borderColor: COLORS.primary },
  toggleText: { fontSize: 13, color: COLORS.muted },
  toggleTextActive: { color: '#fff', fontWeight: '700' },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 14,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderColor: COLORS.border,
    gap: 8,
  },
  rowActive: { backgroundColor: '#eef5f0' },
  name: { fontSize: 15, fontWeight: '600' },
  meta: { fontSize: 12, color: COLORS.muted, marginTop: 2 },
});
