/**
 * Sección Fases: lista con barra de progreso y registro rápido de avance
 * (operación append-only progress_update).
 */
import { useFocusEffect } from '@react-navigation/native';
import React, { useCallback, useState } from 'react';
import { ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { Phase } from '../../api/types';
import { hasPermission, useSession } from '../../auth/session';
import { getPhases } from '../../db/repositories';
import { recordProgressUpdate } from '../../sync/mutations';
import { Card, COLORS, EmptyState } from '../../ui/components';
import { useLayout } from '../../ui/responsive';

const QUICK = [25, 50, 75, 100];

export function PhasesSection({ projectId }: { projectId: number }) {
  const { user } = useSession();
  const canProgress = hasPermission(user, 'update progress');
  const { columns, gutter } = useLayout();
  const [phases, setPhases] = useState<Phase[]>([]);

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

  useFocusEffect(load);

  const onQuick = useCallback(
    async (phase: Phase, progress: number) => {
      await recordProgressUpdate({ phase_id: phase.id, progress });
      // Reflejo optimista en la barra (el valor real llega en el próximo PULL).
      setPhases((prev) =>
        prev.map((p) => (p.id === phase.id ? { ...p, progress_percent: progress } : p)),
      );
    },
    [],
  );

  if (phases.length === 0) return <EmptyState text="Sin fases." />;

  return (
    <ScrollView contentContainerStyle={[styles.body, { padding: gutter }]}>
      <View style={[styles.grid, columns > 1 && { gap: gutter }]}>
        {phases.map((p) => {
          const pct = Math.round(p.progress_percent ?? 0);
          return (
            <Card key={p.id} style={[styles.card, columns > 1 && { width: `${100 / columns - 2}%` }]}>
              <View style={styles.headerRow}>
                {p.color ? <View style={[styles.dot, { backgroundColor: p.color }]} /> : null}
                <Text style={styles.name}>{p.name}</Text>
                <Text style={styles.pct}>{pct}%</Text>
              </View>
              <View style={styles.track}>
                <View style={[styles.fill, { width: `${pct}%` }]} />
              </View>
              {canProgress && (
                <View style={styles.quickRow}>
                  {QUICK.map((q) => (
                    <TouchableOpacity key={q} style={styles.quickBtn} onPress={() => void onQuick(p, q)}>
                      <Text style={styles.quickText}>{q}%</Text>
                    </TouchableOpacity>
                  ))}
                </View>
              )}
            </Card>
          );
        })}
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  body: { gap: 10 },
  grid: { flexDirection: 'row', flexWrap: 'wrap', gap: 10 },
  card: { width: '100%', gap: 8 },
  headerRow: { flexDirection: 'row', alignItems: 'center', gap: 8 },
  dot: { width: 12, height: 12, borderRadius: 6 },
  name: { fontSize: 15, fontWeight: '600', flex: 1 },
  pct: { fontSize: 13, color: COLORS.muted },
  track: { height: 8, borderRadius: 4, backgroundColor: '#e3e3e3', overflow: 'hidden' },
  fill: { height: '100%', backgroundColor: COLORS.primary },
  quickRow: { flexDirection: 'row', gap: 6 },
  quickBtn: {
    paddingHorizontal: 10,
    paddingVertical: 5,
    borderRadius: 6,
    borderWidth: 1,
    borderColor: COLORS.border,
  },
  quickText: { fontSize: 12, color: COLORS.muted, fontWeight: '600' },
});
