import { useState } from 'react';
import { View, Text, StyleSheet, Pressable, ActivityIndicator } from 'react-native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { useActivityHistory, useDeleteActivity } from '../hooks/useActivity';
import { ActivityChart } from './ActivityChart';
import { ActivityPeriod } from '../../../api/activity';
import { colors, spacing, radii, typography } from '../../../theme';
import { formatDuration } from '../utils/format';
import { confirmAlert } from '../../../utils/alert';

const PERIODS: { value: ActivityPeriod; label: string }[] = [
  { value: 'semaine', label: 'Semaine' },
  { value: 'mois', label: 'Mois' },
];

export function ActivityHistorySection() {
  const [period, setPeriod] = useState<ActivityPeriod>('semaine');
  const { data, isLoading } = useActivityHistory(period);
  const deleteActivity = useDeleteActivity(period);

  const overview = data?.overview;

  function handleDelete(id: number, label: string) {
    confirmAlert('Supprimer l\'activité', `Supprimer l'activité du ${label} ?`, 'Supprimer', () => {
      deleteActivity.mutate(id);
    });
  }

  return (
    <View style={styles.card}>
      <View style={styles.header}>
        <View style={styles.headerTitle}>
          <Ionicons name="walk-outline" size={18} color={colors.primary} />
          <Text style={styles.title}>Activité physique</Text>
        </View>
        <View style={styles.tabs}>
          {PERIODS.map((p) => {
            const active = p.value === period;
            return (
              <Pressable key={p.value} style={[styles.tab, active && styles.tabActive]} onPress={() => setPeriod(p.value)}>
                <Text style={[styles.tabText, active && styles.tabTextActive]}>{p.label}</Text>
              </Pressable>
            );
          })}
        </View>
      </View>

      {isLoading || !overview ? (
        <ActivityIndicator color={colors.primary} style={styles.loader} />
      ) : (
        <>
          {overview.totalMinutes > 0 && (
            <Text style={styles.total}>{formatDuration(overview.totalMinutes)} au total sur la période</Text>
          )}

          {overview.hasData ? (
            <ActivityChart points={overview.points} />
          ) : (
            <Text style={styles.empty}>Aucune activité sur cette période.</Text>
          )}

          {overview.entries.length > 0 && (
            <View style={styles.list}>
              {overview.entries.map((entry) => (
                <View key={entry.id} style={styles.row}>
                  <Text style={styles.rowDate}>{entry.label}</Text>
                  <View style={styles.rowMain}>
                    <Text style={styles.rowDescription} numberOfLines={1}>
                      {entry.description}
                    </Text>
                    {entry.durationMinutes != null && (
                      <Text style={styles.rowDuration}>{formatDuration(entry.durationMinutes)}</Text>
                    )}
                  </View>
                  <Pressable
                    style={styles.deleteButton}
                    onPress={() => handleDelete(entry.id, entry.label)}
                    hitSlop={8}
                  >
                    <Ionicons name="trash-outline" size={16} color={colors.danger} />
                  </Pressable>
                </View>
              ))}
            </View>
          )}
        </>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  card: { backgroundColor: colors.card, borderRadius: radii.lg, padding: spacing.md, gap: spacing.sm },
  header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: spacing.sm, flexWrap: 'wrap' },
  headerTitle: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
  title: { ...typography.caption, fontWeight: '700', color: colors.textMuted },
  tabs: { flexDirection: 'row', backgroundColor: colors.surface, borderRadius: radii.pill, padding: 3, gap: 2 },
  tab: { paddingHorizontal: spacing.md, paddingVertical: spacing.sm, borderRadius: radii.pill },
  tabActive: { backgroundColor: colors.card },
  tabText: { fontSize: 13, fontWeight: '700', color: colors.textMuted },
  tabTextActive: { color: colors.primary },
  total: { fontSize: 13, fontWeight: '800', color: colors.textMuted },
  loader: { paddingVertical: spacing.xl },
  empty: { ...typography.caption, color: colors.textMuted, textAlign: 'center', paddingVertical: spacing.xl },
  list: { gap: spacing.xs },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.sm,
    paddingVertical: spacing.sm,
    borderTopWidth: 1,
    borderTopColor: colors.border,
  },
  rowDate: { fontSize: 12, fontWeight: '700', color: colors.textMuted, width: 40 },
  rowMain: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: spacing.sm },
  rowDescription: { flex: 1, fontSize: 14, fontWeight: '600', color: colors.text },
  rowDuration: { fontSize: 13, fontWeight: '700', color: colors.textMuted },
  deleteButton: { padding: 4 },
});
