import React, { useState } from 'react';
import { View, Text, Pressable, StyleSheet, TextInput } from 'react-native';
import { useRouter } from 'expo-router';
import { useUsers } from '@/contexts/UserContext';
import { useId4a } from '@/contexts/Id4aContext';
import fichier_4a from '@/assets/json/fichier_4a.json';
import fichier_8a from '@/assets/json/fichier_8a.json';
import symptomes from '@/assets/json/symptomes.json';
import { useAdmin } from '@/contexts/AdminContext';
import { useReturnMemory } from '@/contexts/ReturnMemoryContext';

export default function PopupCode({ onClose }: { onClose: () => void }) {
  const [code, setCode] = useState('');
  const [errorMessage, setErrorMessage] = useState('');
  const { users, setCurrentRole } = useUsers();
  const { setId4a } = useId4a();
  const router = useRouter();
  const { clearReturnMemory, setReturnMemory } = useReturnMemory();
  const {
    setAdmin, setReeduc, setGeron, setKine, setErgo, setInfirmiere, setNaturo,
  } = useAdmin();

  const symptomCode = symptomes.find(s => s.id === 5);

  const resetAllRoles = () => {
    setAdmin(false);
    setReeduc(false);
    setGeron(false);
    setKine(false);
    setErgo(false);
    setInfirmiere(false);
    setNaturo(false);
    clearReturnMemory();
  };

  const navigateTo = (id: number) => {
    setId4a(id);
    setReturnMemory(id);
    onClose();

    const node4a = fichier_4a.find(n => n.id === id);
    const node8a = fichier_8a.find(n => n.id === node4a?.id_8a);
    const href = node8a?.href;

    if (!href || href === '/') {
      router.replace('/');
    } else if (href === '/(tabs)') {
      router.replace('/(tabs)/');
    } else {
      router.replace({ pathname: href as any, params: { id_4a: id } });
    }
  };

  const handleValider = () => {
    if (!code.trim()) return;
    const trimmed = code.trim();
    const firstChar = trimmed[0].toUpperCase();

    switch (firstChar) {
      case 'M': // ← rôle par défaut
        resetAllRoles();
        setCurrentRole?.(null);
        navigateTo(350);
        break;
      case 'A':
        resetAllRoles();
        setAdmin(true);
        setCurrentRole?.('admin');
        navigateTo(users.length > 0 ? 86 : 319);
        break;
      case 'R':
        resetAllRoles();
        setReeduc(true);
        setCurrentRole?.('reeduc');
        navigateTo(users.length > 0 ? 351 : 319);
        break;
      case 'G':
        resetAllRoles();
        setGeron(true);
        setCurrentRole?.('geron');
        navigateTo(users.length > 0 ? 352 : 319);
        break;
      case 'K':
        resetAllRoles();
        setKine(true);
        setCurrentRole?.('kine');
        navigateTo(users.length > 0 ? 292 : 319);
        break;
      case 'E':
        resetAllRoles();
        setErgo(true);
        setCurrentRole?.('ergo');
        navigateTo(users.length > 0 ? 293 : 319);
        break;
      case 'I':
        resetAllRoles();
        setInfirmiere(true);
        setCurrentRole?.('infirmiere');
        navigateTo(users.length > 0 ? 294 : 319);
        break;
      case 'N':
        resetAllRoles();
        setNaturo(true);
        setCurrentRole?.('naturo');
        navigateTo(users.length > 0 ? 290 : 319);
        break;
      case 'B':
      case 'C':
      case 'D':
      case 'F':
        setErrorMessage('Cette page est réservée aux développeurs et en cours de préparation.');
        break;
      default:
        setErrorMessage("Ce code n'existe pas.");
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.text}>
        Votre code vous a été donné par le Dr Mathieu. Vous pouvez le redemander sur
        J.mathieu@clinimeter.com. En attendant, vous pouvez mettre votre année de naissance.
      </Text>

      {symptomCode && <Text style={styles.label}>{symptomCode.name}</Text>}

      <TextInput
        value={code}
        onChangeText={val => { setCode(val); setErrorMessage(''); }}
        placeholder="Entrez votre code"
        placeholderTextColor="#aaa"
        style={styles.input}
        autoCapitalize="characters"
        returnKeyType="done"
        onSubmitEditing={handleValider}
      />

      {errorMessage !== '' && <Text style={styles.error}>{errorMessage}</Text>}

      <View style={styles.buttonRow}>
        <Pressable onPress={onClose} style={[styles.button, styles.cancelButton]}>
          <Text style={{ color: 'black' }}>Annuler</Text>
        </Pressable>
        <Pressable onPress={handleValider} style={[styles.button, styles.validateButton]}>
          <Text style={{ color: 'white' }}>Valider</Text>
        </Pressable>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { padding: 20 },
  text: { fontSize: 16, marginBottom: 16 },
  label: { fontSize: 14, fontWeight: '600', marginBottom: 6, color: '#333' },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 8,
    fontSize: 16,
    marginBottom: 12,
    color: 'black',
  },
  error: { color: '#E8437B', fontSize: 13, marginBottom: 12, textAlign: 'center' },
  buttonRow: { flexDirection: 'row', justifyContent: 'space-between', gap: 12 },
  button: { flex: 1, padding: 10, borderRadius: 8, alignItems: 'center' },
  cancelButton: { backgroundColor: '#eee' },
  validateButton: { backgroundColor: '#E8437B' },
});