/**
 * Contenido del detalle de una feature: estado/progreso editable, inspecciones
 * y fotos. Reutilizado en móvil (pantalla) y tablet (panel del maestro-detalle).
 */
import { 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 { Feature, Inspection } from '../../api/types';
import { hasPermission, useSession } from '../../auth/session';
import { getFeature, getInspectionsByFeature } from '../../db/repositories';
import { updateFeature } from '../../sync/mutations';
import { RootStackParamList } from '../../navigation/types';
import {
  Badge,
  Card,
  ChipSelect,
  COLORS,
  EmptyState,
  PrimaryButton,
  SectionTitle,
} from '../../ui/components';
import { MediaStrip } from '../../ui/MediaStrip';

const STATUSES = ['pending', 'in_progress', 'completed', 'blocked'] as const;
const QUICK_PROGRESS = [0, 25, 50, 75, 100];

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 refresh = useCallback(async () => {
    const [f, ins] = await Promise.all([
      getFeature(featureId),
      getInspectionsByFeature(featureId),
    ]);
    setFeature(f);
    setInspections(ins);
  }, [featureId]);

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

  const onStatus = useCallback(
    async (status: string) => {
      await updateFeature({ id: featureId, status });
      await refresh();
    },
    [featureId, refresh],
  );

  const onProgress = useCallback(
    async (progress: number) => {
      await updateFeature({ id: featureId, progress });
      await refresh();
    },
    [featureId, refresh],
  );

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

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

      <MediaStrip
        parentEntity="feature"
        parentId={feature.id}
        canUpload={hasPermission(user, 'upload media')}
      />

      {canProgress && (
        <Card style={styles.editCard}>
          <ChipSelect
            label="Estado"
            value={feature.status as (typeof STATUSES)[number] | undefined}
            options={STATUSES}
            onChange={(v) => void onStatus(v)}
          />
          <Text style={styles.fieldLabel}>Progreso</Text>
          <View style={styles.progressRow}>
            {QUICK_PROGRESS.map((p) => {
              const active = Math.round(feature.progress ?? 0) === p;
              return (
                <TouchableOpacity
                  key={p}
                  style={[styles.pBtn, active && styles.pBtnActive]}
                  onPress={() => void onProgress(p)}
                >
                  <Text style={[styles.pText, active && styles.pTextActive]}>{p}%</Text>
                </TouchableOpacity>
              );
            })}
          </View>
        </Card>
      )}

      <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>
      ))}
      {canInspect && (
        <PrimaryButton
          title="Nueva inspección"
          variant="ghost"
          onPress={() =>
            navigation.navigate('InspectionForm', {
              featureId: feature.id,
              featureName: feature.name,
              templateId: feature.template_id ?? undefined,
            })
          }
        />
      )}
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  center: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  body: { padding: 16, gap: 6 },
  title: { fontSize: 20, fontWeight: '700' },
  badges: { flexDirection: 'row', gap: 6, marginTop: 6 },
  editCard: { marginTop: 12 },
  fieldLabel: { fontSize: 13, color: COLORS.muted, marginBottom: 6, fontWeight: '600' },
  progressRow: { flexDirection: 'row', gap: 6, flexWrap: 'wrap' },
  pBtn: {
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: COLORS.border,
    backgroundColor: '#fff',
  },
  pBtnActive: { backgroundColor: COLORS.primary, borderColor: COLORS.primary },
  pText: { color: COLORS.muted, fontWeight: '600' },
  pTextActive: { color: '#fff' },
  insCard: { marginBottom: 6 },
  insTitle: { fontSize: 14, fontWeight: '600' },
  insNotes: { fontSize: 13, color: COLORS.muted, marginTop: 2 },
});
