import { useEffect, useState } from 'react';
import { View, Text, StyleSheet, Pressable, Modal, ActivityIndicator } from 'react-native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { useAccount } from '../../profile/hooks/useAccount';
import { JournalEvent } from '../../../api/tracking';
import { colors, spacing, radii, typography } from '../../../theme';

type Props = {
  visible: boolean;
  entry: JournalEvent | null;
  onClose: () => void;
  onShare: (memberIds: number[]) => void;
  submitting: boolean;
};

// Popin de partage explicite (icône partage du journal, `JournalSection.tsx`) — choix
// d'un ou plusieurs membres de la famille à qui pousser cette entrée en priorité dans
// leurs suggestions (`TrackingService::shareEntry()`, origin=SHARED). Disponible aussi
// bien aujourd'hui que sur une entrée d'historique.
export function ShareEntryModal({ visible, entry, onClose, onShare, submitting }: Props) {
  const { data: account } = useAccount();
  const [selected, setSelected] = useState<number[]>([]);

  useEffect(() => {
    if (visible) setSelected([]);
  }, [visible, entry]);

  if (!entry) return null;

  const members = (account?.family?.members ?? []).filter((m) => !m.isSelf);

  function toggle(id: number) {
    setSelected((list) => (list.includes(id) ? list.filter((m) => m !== id) : [...list, id]));
  }

  return (
    <Modal visible={visible} transparent animationType="fade" onRequestClose={onClose}>
      <Pressable style={styles.scrim} onPress={onClose}>
        <Pressable style={styles.card} onPress={(e) => e.stopPropagation()}>
          <View style={styles.header}>
            <Ionicons name="share-social-outline" size={18} color={colors.primary} />
            <Text style={styles.title}>Partager avec la famille</Text>
            <Pressable onPress={onClose} hitSlop={10}>
              <Ionicons name="close" size={20} color={colors.textMuted} />
            </Pressable>
          </View>

          <Text style={styles.nom}>{entry.nom}</Text>

          {members.length === 0 ? (
            <Text style={styles.empty}>Aucun autre membre dans votre famille pour l'instant.</Text>
          ) : (
            <View style={styles.list}>
              {members.map((member) => {
                const isSelected = selected.includes(member.id);
                return (
                  <Pressable key={member.id} style={styles.row} onPress={() => toggle(member.id)}>
                    <View style={[styles.checkbox, isSelected && styles.checkboxActive]}>
                      {isSelected && <Ionicons name="checkmark" size={14} color="#fff" />}
                    </View>
                    <Text style={styles.rowText}>{member.name}</Text>
                  </Pressable>
                );
              })}
            </View>
          )}

          <Pressable
            style={[styles.shareButton, (submitting || selected.length === 0) && styles.shareButtonDisabled]}
            disabled={submitting || selected.length === 0}
            onPress={() => onShare(selected)}
          >
            {submitting ? <ActivityIndicator color="#fff" /> : <Text style={styles.shareButtonText}>Partager</Text>}
          </Pressable>
        </Pressable>
      </Pressable>
    </Modal>
  );
}

const styles = StyleSheet.create({
  scrim: { flex: 1, backgroundColor: 'rgba(20,22,45,0.4)', justifyContent: 'center', padding: spacing.lg },
  card: { backgroundColor: colors.card, borderRadius: radii.lg, padding: spacing.lg, gap: spacing.sm },
  header: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
  title: { ...typography.body, fontWeight: '700', fontSize: 17, color: colors.text, flex: 1 },
  nom: { ...typography.title, fontSize: 18, color: colors.text },
  empty: { ...typography.body, color: colors.textMuted, fontSize: 14 },
  list: { gap: spacing.xs },
  row: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, paddingVertical: spacing.xs },
  checkbox: {
    width: 22,
    height: 22,
    borderRadius: radii.sm,
    borderWidth: 1,
    borderColor: colors.border,
    alignItems: 'center',
    justifyContent: 'center',
  },
  checkboxActive: { backgroundColor: colors.primary, borderColor: colors.primary },
  rowText: { ...typography.body, fontSize: 15, color: colors.text },
  shareButton: { backgroundColor: colors.primary, borderRadius: radii.md, paddingVertical: spacing.sm + 2, alignItems: 'center', marginTop: spacing.sm },
  shareButtonDisabled: { backgroundColor: colors.border },
  shareButtonText: { ...typography.body, color: '#fff', fontWeight: '700' },
});
