import { useState } from 'react';
import { View, Text, StyleSheet, ScrollView, ActivityIndicator, TextInput, Pressable, Alert } from 'react-native';
import { useAccount, useGenerateInvitationCode, useInviteMember, useJoinFamily, useLeaveFamily, useRemoveMember } from '../hooks/useAccount';
import { colors, spacing, radii, typography } from '../../../theme';

function initialOf(name: string | null, email: string): string {
  return (name ?? email).slice(0, 1).toUpperCase();
}

export function AccountScreen() {
  const { data, isLoading, error } = useAccount();
  const generateCode = useGenerateInvitationCode();
  const join = useJoinFamily();
  const invite = useInviteMember();
  const leave = useLeaveFamily();
  const remove = useRemoveMember();
  const [code, setCode] = useState('');
  const [inviteEmail, setInviteEmail] = useState('');

  function reportError(err: unknown) {
    Alert.alert('Erreur', err instanceof Error ? err.message : 'Une erreur est survenue.');
  }

  function handleJoin() {
    if (code.trim() === '') return;
    join.mutate(code.trim(), {
      onSuccess: () => setCode(''),
      onError: reportError,
    });
  }

  function handleInvite() {
    if (inviteEmail.trim() === '') return;
    invite.mutate(inviteEmail.trim(), {
      onSuccess: () => {
        setInviteEmail('');
        Alert.alert('Invitation envoyée', `Un email a été envoyé à ${inviteEmail.trim()}.`);
      },
      onError: reportError,
    });
  }

  function confirmLeave() {
    Alert.alert('Quitter la famille ?', undefined, [
      { text: 'Annuler', style: 'cancel' },
      { text: 'Quitter', style: 'destructive', onPress: () => leave.mutate(undefined, { onError: reportError }) },
    ]);
  }

  function confirmRemove(id: number, name: string) {
    Alert.alert(`Retirer ${name} de la famille ?`, undefined, [
      { text: 'Annuler', style: 'cancel' },
      { text: 'Retirer', style: 'destructive', onPress: () => remove.mutate(id, { onError: reportError }) },
    ]);
  }

  if (isLoading) {
    return (
      <View style={styles.center}>
        <ActivityIndicator color={colors.primary} />
      </View>
    );
  }

  if (error || !data) {
    return (
      <View style={styles.center}>
        <Text style={typography.body}>Impossible de charger le compte.</Text>
      </View>
    );
  }

  const { family } = data;
  const canLeave = family !== null && (!family.isCreator || family.members.length <= 1);

  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.content}>
      <View>
        <Text style={styles.title}>Mon compte</Text>
        <Text style={styles.subtitle}>
          Rattachez les comptes de votre famille pour partager vos recettes favorites et votre planning des repas.
        </Text>
      </View>

      <View style={styles.card}>
        <View style={styles.identity}>
          <View style={styles.avatar}>
            <Text style={styles.avatarText}>{initialOf(data.firstname, data.email)}</Text>
          </View>
          <View style={styles.identityInfo}>
            <Text style={styles.identityName}>{data.firstname ?? data.email}</Text>
            <Text style={styles.identityEmail}>{data.email}</Text>
          </View>
          <View style={styles.badge}>
            <Text style={styles.badgeText}>{data.licence.label}</Text>
          </View>
        </View>
      </View>

      <View style={styles.card}>
        <Text style={styles.cardTitle}>Famille</Text>

        {family === null ? (
          <>
            <Text style={styles.hint}>
              Vous n'êtes rattaché à aucune famille. Générez un code à communiquer à vos proches, ou saisissez le code
              qu'ils vous ont transmis.
            </Text>

            <Pressable
              style={[styles.button, styles.buttonPrimary]}
              onPress={() => generateCode.mutate(undefined, { onError: reportError })}
              disabled={generateCode.isPending}
            >
              <Text style={styles.buttonPrimaryText}>Générer mon code d'invitation</Text>
            </Pressable>

            <View style={styles.joinRow}>
              <TextInput
                style={styles.joinInput}
                placeholder="Code reçu (ex. AB3D9F2K)"
                placeholderTextColor={colors.textMuted}
                autoCapitalize="characters"
                maxLength={10}
                value={code}
                onChangeText={setCode}
              />
              <Pressable style={styles.button} onPress={handleJoin} disabled={join.isPending}>
                <Text style={styles.buttonText}>Rejoindre</Text>
              </Pressable>
            </View>

            <Text style={styles.hint}>Ou invitez directement un proche par email :</Text>
            <View style={styles.joinRow}>
              <TextInput
                style={styles.joinInput}
                placeholder="Email du proche à inviter"
                placeholderTextColor={colors.textMuted}
                autoCapitalize="none"
                keyboardType="email-address"
                value={inviteEmail}
                onChangeText={setInviteEmail}
              />
              <Pressable style={styles.button} onPress={handleInvite} disabled={invite.isPending}>
                <Text style={styles.buttonText}>Inviter</Text>
              </Pressable>
            </View>
          </>
        ) : (
          <>
            {family.isCreator ? (
              <>
                <Text style={styles.hint}>
                  Vous gérez cette famille. Communiquez ce code à vos proches pour qu'ils rattachent leur compte.
                </Text>
                <View style={styles.codeBox}>
                  <Text style={styles.codeText}>{family.invitationCode}</Text>
                </View>

                <View style={styles.joinRow}>
                  <TextInput
                    style={styles.joinInput}
                    placeholder="Email du proche à inviter"
                    placeholderTextColor={colors.textMuted}
                    autoCapitalize="none"
                    keyboardType="email-address"
                    value={inviteEmail}
                    onChangeText={setInviteEmail}
                  />
                  <Pressable style={styles.button} onPress={handleInvite} disabled={invite.isPending}>
                    <Text style={styles.buttonText}>Inviter</Text>
                  </Pressable>
                </View>
              </>
            ) : (
              <Text style={styles.hint}>
                Vous faites partie de la famille de <Text style={styles.hintStrong}>{family.creatorName}</Text>. Vos
                recettes favorites et votre planning des repas sont partagés avec elle.
              </Text>
            )}

            <View style={styles.members}>
              {family.members.map((member) => (
                <View key={member.id} style={styles.member}>
                  <View style={styles.memberInfo}>
                    <View style={styles.avatarSm}>
                      <Text style={styles.avatarSmText}>{initialOf(member.name, member.email)}</Text>
                    </View>
                    <View>
                      <Text style={styles.memberName}>
                        {member.name}
                        {member.isCreator ? <Text style={styles.tag}> Gestionnaire</Text> : null}
                      </Text>
                      <Text style={styles.memberEmail}>{member.email}</Text>
                    </View>
                  </View>
                  {family.isCreator && !member.isSelf ? (
                    <Pressable
                      style={[styles.button, styles.buttonDanger]}
                      onPress={() => confirmRemove(member.id, member.name)}
                      disabled={remove.isPending}
                    >
                      <Text style={styles.buttonDangerText}>Retirer</Text>
                    </Pressable>
                  ) : null}
                </View>
              ))}
            </View>

            {family.isCreator && !canLeave ? (
              <Text style={styles.hint}>Retirez les autres membres avant de pouvoir quitter la famille.</Text>
            ) : (
              <Pressable style={[styles.button, styles.buttonGhost]} onPress={confirmLeave} disabled={leave.isPending}>
                <Text style={styles.buttonText}>Quitter la famille</Text>
              </Pressable>
            )}
          </>
        )}
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: colors.background },
  content: { padding: spacing.lg, gap: spacing.md },
  center: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.background },
  title: { ...typography.title, color: colors.text },
  subtitle: { ...typography.caption, color: colors.textMuted, marginTop: spacing.xs },
  card: { backgroundColor: colors.card, borderRadius: radii.lg, padding: spacing.md, gap: spacing.sm },
  cardTitle: { ...typography.body, fontWeight: '700', color: colors.text },
  identity: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
  identityInfo: { flex: 1 },
  identityName: { ...typography.body, fontWeight: '700', color: colors.text },
  identityEmail: { ...typography.caption, color: colors.textMuted },
  avatar: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
  },
  avatarText: { color: '#fff', fontWeight: '700', fontSize: 18 },
  avatarSm: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
  },
  avatarSmText: { color: '#fff', fontWeight: '700', fontSize: 13 },
  badge: { backgroundColor: colors.surface, borderRadius: radii.pill, paddingHorizontal: spacing.sm, paddingVertical: 4 },
  badgeText: { ...typography.caption, fontWeight: '700', color: colors.text },
  hint: { ...typography.caption, color: colors.textMuted },
  hintStrong: { color: colors.text, fontWeight: '700' },
  codeBox: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.md,
    paddingVertical: spacing.md,
    alignItems: 'center',
    backgroundColor: colors.surface,
  },
  codeText: { fontSize: 22, fontWeight: '700', letterSpacing: 4, color: colors.text },
  joinRow: { flexDirection: 'row', gap: spacing.sm },
  joinInput: {
    flex: 1,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.sm,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.sm,
    color: colors.text,
  },
  members: { gap: spacing.sm },
  member: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: spacing.sm },
  memberInfo: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, flex: 1 },
  memberName: { ...typography.body, fontSize: 14, fontWeight: '700', color: colors.text },
  memberEmail: { ...typography.caption, color: colors.textMuted },
  tag: { ...typography.caption, color: colors.primary, fontWeight: '700' },
  button: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    borderRadius: radii.md,
    borderWidth: 1,
    borderColor: colors.border,
  },
  buttonText: { ...typography.body, fontSize: 14, fontWeight: '700', color: colors.text },
  buttonPrimary: { backgroundColor: colors.primary, borderColor: colors.primary },
  buttonPrimaryText: { ...typography.body, fontSize: 14, fontWeight: '700', color: '#fff' },
  buttonGhost: { alignSelf: 'flex-start' },
  buttonDanger: { borderColor: colors.danger },
  buttonDangerText: { ...typography.body, fontSize: 14, fontWeight: '700', color: colors.danger },
});
