import { Feature, FeatureType, Inspection } from '../../api/types';
import { hasPermission, useSession } from '../../auth/session';
import { getFeature, getFeatureTypes, getInspectionsByFeature } from '../../db/repositories';
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import React, { useCallback, useEffect, useState } from 'react';
import { ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { RootStackParamList } from '../../navigation/types';
import {
  Badge,
  Card,
  COLORS,
  EmptyState,
  SectionTitle,
} from '../../ui/components';

type Nav = NativeStackNavigationProp<RootStackParamList>;

export function FeatureDetailContent({ featureId }: { featureId: number }) {
  const navigation = useNavigation<Nav>();
  const { user } = useSession();
  const canProgress = hasPermission(user, 'update progress');
  const canInspect = hasPermission(user, 'create inspections');

  const [feature, setFeature] = useState<Feature | null>(null);
  const [inspections, setInspections] = useState<Inspection[]>([]);
  const [featureTypes, setFeatureTypes] = useState<FeatureType[]>([]);

  // Header right button for Nueva inspección
  // MOVIDO AQUÍ: Los hooks deben ir siempre antes de cualquier return.
  useFocusEffect(
    useCallback(() => {
      if (canInspect && feature) {
        navigation.setOptions({
          headerRight: () => (
            <TouchableOpacity
              style={styles.headerButton}
              onPress={() =>
                navigation.navigate('InspectionForm', {
                  featureId: feature.id,
                  featureName: feature.name,
                  templateId: feature.template_id ?? undefined,
                })
              }
            >
              <Text style={styles.headerButtonText}>+ Inspección</Text>
            </TouchableOpacity>
          ),
        });
      }
      return () => {
        navigation.setOptions({ headerRight: undefined });
      };
    }, [navigation, canInspect, feature]),
  );

  const refresh = useCallback(async () => {
    const [f, ins, types] = await Promise.all([
      getFeature(featureId),
      getInspectionsByFeature(featureId),
      getFeatureTypes(),
    ]);
    setFeature(f);
    setInspections(ins);
    setFeatureTypes(types);
  }, [featureId]);

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

  if (!feature) {
    return (
      <View style={styles.center}>
        <Text style={{ color: COLORS.muted }}>Cargando…</Text>
      </View>
    );
  }

  const featureType = featureTypes.find((t) => t.id === feature.feature_type_id);
  const isActive = feature.is_active == null || Number(feature.is_active) !== 0;

  return (
    <ScrollView contentContainerStyle={styles.body}>
      <View style={styles.badges}>
        {featureType && (
          <Badge label={featureType.name} color={featureType.color ?? COLORS.muted} />
        )}
        <Badge label={`${Math.round(feature.progress ?? 0)}%`} color={COLORS.muted} />
      </View>

      <SectionTitle>Inspecciones ({inspections.length})</SectionTitle>
      {inspections.length === 0 && <EmptyState text="Sin inspecciones." />}
      {inspections.map((ins) => (
        <Card key={ins.id} style={styles.insCard}>
          <Text style={styles.insTitle}>
            {ins.result ?? ins.status ?? 'Inspección'} ·{' '}
            {ins.created_at ? new Date(ins.created_at).toLocaleDateString() : ''}
          </Text>
          {ins.notes ? <Text style={styles.insNotes}>{ins.notes}</Text> : null}
        </Card>
      ))}
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  center: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  body: { padding: 16, gap: 6 },
  badges: { flexDirection: 'row', gap: 6, marginTop: 6 },
  insCard: { marginBottom: 6 },
  insTitle: { fontSize: 14, fontWeight: '600' },
  insNotes: { fontSize: 13, color: COLORS.muted, marginTop: 2 },
  headerButton: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    backgroundColor: COLORS.primary,
    borderRadius: 6,
    marginRight: 8,
  },
  headerButtonText: {
    color: '#fff',
    fontWeight: '600',
    fontSize: 13,
  },
});
