import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:nfc_manager/nfc_manager.dart';

import 'google_sheets_api.dart';

class InscriptionPage extends StatefulWidget {
  final String? prefilledMac; // valeur scannée
  final String scanType; // "QR" ou "NFC"

  const InscriptionPage({super.key, this.prefilledMac, required this.scanType});

  @override
  State<InscriptionPage> createState() => _InscriptionPageState();
}

class _InscriptionPageState extends State<InscriptionPage> {
  final _formKey = GlobalKey<FormState>();

  final TextEditingController _numController = TextEditingController();
  final TextEditingController _firstController = TextEditingController();
  final TextEditingController _lastController = TextEditingController();
  final TextEditingController _macController = TextEditingController();
  final TextEditingController _qrController = TextEditingController();

  bool _hasNfc = false;
  bool _isScanning = false;

  bool _loadingStudents = false;
  List<StudentItem> _students = const [];
  StudentItem? _selectedStudent;

  final Color _primaryColor = const Color(0xFF4361EE);
  final Color _successColor = const Color(0xFF06D6A0);

  @override
  void initState() {
    super.initState();

    final prefilled = (widget.prefilledMac ?? '').trim();
    if (prefilled.isNotEmpty) {
      if (widget.scanType == 'QR') {
        _qrController.text = prefilled;
      } else {
        _macController.text = prefilled;
        _hasNfc = true;
      }
    }

    _loadStudents();
  }

  Future<void> _loadStudents() async {
    setState(() => _loadingStudents = true);
    try {
      final api = GoogleSheetsApi();
      final items = await api.listStudentsForDropdown();
      if (!mounted) return;
      setState(() => _students = items);
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Erreur chargement étudiants: $e')),
      );
    } finally {
      if (mounted) setState(() => _loadingStudents = false);
    }
  }

  void _applySelectedStudent(StudentItem? s) {
    setState(() {
      _selectedStudent = s;
      if (s == null) return;

      if (_numController.text.isEmpty) _numController.text = s.number;
      if (_firstController.text.isEmpty) _firstController.text = s.firstName;
      if (_lastController.text.isEmpty) _lastController.text = s.lastName;

      if (_macController.text.isEmpty && (s.nfc ?? '').trim().isNotEmpty) {
        _macController.text = s.nfc!.trim();
        _hasNfc = true;
      }
      if (_qrController.text.isEmpty && (s.qr ?? '').trim().isNotEmpty) {
        _qrController.text = s.qr!.trim();
      }
    });
  }

  Future<void> _scanNfcAndFill() async {
    if (_isScanning) return;

    final available = await NfcManager.instance.isAvailable();
    if (!available) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('NFC non disponible')),
      );
      return;
    }

    if (!mounted) return;
    setState(() => _isScanning = true);

    try {
      NfcManager.instance.startSession(
        pollingOptions: {
          NfcPollingOption.iso14443,
          NfcPollingOption.iso15693,
          NfcPollingOption.iso18092,
        },
        onDiscovered: (NfcTag tag) async {
          String uid = '';

          try {
            dynamic data;
            try {
              data = (tag as dynamic).data;
            } catch (_) {
              data = null;
            }

            final idBytes = _safeLookup(data, 'id');
            if (idBytes != null) {
              uid = _bytesToUid(idBytes);
            } else {
              try {
                uid = _bytesToUid((tag as dynamic).id);
              } catch (_) {
                uid = '';
              }
            }

            if (uid.trim().isEmpty) {
              if (mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('UID introuvable')),
                );
              }
            } else {
              if (mounted) {
                setState(() {
                  _macController.text = uid;
                  _hasNfc = true;
                });
              }
            }
          } catch (e) {
            if (mounted) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('Erreur lecture NFC: $e')),
              );
            }
          } finally {
            try {
              await NfcManager.instance.stopSession();
            } catch (_) {}

            if (mounted) setState(() => _isScanning = false);
          }
        },
      );
    } catch (e) {
      if (mounted) {
        setState(() => _isScanning = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Impossible de démarrer le NFC: $e')),
        );
      }
      try {
        await NfcManager.instance.stopSession();
      } catch (_) {}
    }
  }

  dynamic _safeLookup(dynamic obj, String key) {
    if (obj == null) return null;
    try {
      if (obj is Map) {
        if (obj.containsKey(key)) return obj[key];
        final lower = key.toLowerCase();
        if (obj.containsKey(lower)) return obj[lower];
      }
    } catch (_) {}

    try {
      return (obj as dynamic)[key];
    } catch (_) {}

    try {
      if (key == 'id') return (obj as dynamic).id;
    } catch (_) {}

    return null;
  }

  @override
  void dispose() {
    _numController.dispose();
    _firstController.dispose();
    _lastController.dispose();
    _macController.dispose();
    _qrController.dispose();
    super.dispose();
  }

  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) return;

    final api = GoogleSheetsApi();

    final studentNumber = _numController.text.trim();
    final first = _firstController.text.trim();
    final last = _lastController.text.trim();
    final nfc = _macController.text.trim().isEmpty ? null : _macController.text.trim();
    final qr = _qrController.text.trim().isEmpty ? null : _qrController.text.trim();

    if (_selectedStudent != null) {
      final ok = await api.updateStudentFields(
        rowIndex: _selectedStudent!.rowIndex,
        nfc: nfc,
        qr: qr,
      );
      if (ok && mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('✅ Étudiant mis à jour')),
        );
        Navigator.pop(context);
      }
      return;
    }

    final rowIndex = await api.findRowByStudentNumber(studentNumber);
    if (rowIndex != null) {
      final ok = await api.updateStudentFields(rowIndex: rowIndex, nfc: nfc, qr: qr);
      if (ok && mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('✅ Étudiant mis à jour')),
        );
        Navigator.pop(context);
      }
      return;
    }

    final row = [
      studentNumber,
      first,
      last,
      nfc ?? '',
      qr ?? '',
      DateTime.now().toIso8601String(),
      DateTime.now().toIso8601String(),
    ];

    final ok = await api.appendData(row);
    if (ok && mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('✅ Étudiant enregistré')),
      );
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    final isUpdateMode = _selectedStudent != null;

    return Scaffold(
      backgroundColor: const Color(0xFFF6F8FA),
      appBar: AppBar(
        title: Text(
          isUpdateMode ? 'Mise à jour Étudiant' : 'Inscription Étudiant',
          style: const TextStyle(fontWeight: FontWeight.bold),
        ),
        backgroundColor: _primaryColor,
        foregroundColor: Colors.white,
        elevation: 0,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(12),
        child: Card(
          elevation: 2,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Form(
              key: _formKey,
              child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
                DropdownButtonFormField<StudentItem>(
                  value: _selectedStudent,
                  isExpanded: true,
                  decoration: InputDecoration(
                    labelText: _loadingStudents ? 'Chargement...' : 'Étudiant existant (optionnel)',
                    prefixIcon: Icon(Icons.search, color: _primaryColor),
                    border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
                  ),
                  items: _students
                      .map(
                        (s) => DropdownMenuItem<StudentItem>(
                      value: s,
                      child: Text(s.label, overflow: TextOverflow.ellipsis),
                    ),
                  )
                      .toList(),
                  onChanged: _loadingStudents ? null : _applySelectedStudent,
                ),
                const SizedBox(height: 16),
                _buildTextField(
                  controller: _numController,
                  label: 'N° Étudiant',
                  icon: Icons.badge_rounded,
                  mandatory: true,
                ),
                const SizedBox(height: 16),
                _buildTextField(
                  controller: _firstController,
                  label: 'Prénom',
                  icon: Icons.person_rounded,
                  mandatory: true,
                ),
                const SizedBox(height: 16),
                _buildTextField(
                  controller: _lastController,
                  label: 'Nom',
                  icon: Icons.person_outline_rounded,
                  mandatory: true,
                ),
                const SizedBox(height: 16),

                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.grey.withOpacity(0.05),
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(color: Colors.grey.withOpacity(0.2)),
                  ),
                  child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                    Text(
                      'IDENTIFICATION NFC',
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                        color: Colors.grey.shade600,
                        letterSpacing: 1,
                      ),
                    ),
                    const SizedBox(height: 12),
                    _buildTextField(
                      controller: _macController,
                      label: 'MAC (UID NFC)',
                      icon: Icons.nfc_rounded,
                      mandatory: false,
                    ),
                    const SizedBox(height: 12),
                    Row(children: [
                      Container(
                        padding: const EdgeInsets.all(4),
                        decoration: BoxDecoration(
                          color: _hasNfc ? _successColor.withOpacity(0.1) : Colors.grey.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(6),
                          border: Border.all(color: _hasNfc ? _successColor : Colors.grey),
                        ),
                        child: Row(children: [
                          Checkbox(
                            value: _hasNfc,
                            onChanged: (v) => setState(() => _hasNfc = v ?? false),
                            activeColor: _successColor,
                          ),
                          Text(
                            'NFC détecté',
                            style: TextStyle(
                              color: _hasNfc ? _successColor : Colors.grey,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ]),
                      ),
                      const Spacer(),
                      ElevatedButton.icon(
                        onPressed: _isScanning ? null : _scanNfcAndFill,
                        icon: _isScanning
                            ? const SizedBox(
                          width: 16,
                          height: 16,
                          child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
                        )
                            : const Icon(Icons.nfc_rounded, size: 18),
                        label: Text(_isScanning ? 'Scan...' : 'Scanner'),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: _primaryColor,
                          foregroundColor: Colors.white,
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                        ),
                      ),
                    ]),
                  ]),
                ),

                const SizedBox(height: 16),

                _buildTextField(
                  controller: _qrController,
                  label: 'QR Code (optionnel)',
                  icon: Icons.qr_code_rounded,
                  mandatory: false,
                ),

                const SizedBox(height: 20),

                SizedBox(
                  height: 48,
                  child: ElevatedButton.icon(
                    onPressed: _submit,
                    icon: const Icon(Icons.save_rounded, size: 22),
                    label: Text(
                      isUpdateMode ? 'METTRE À JOUR' : 'ENREGISTRER',
                      style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, letterSpacing: 0.5),
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: _primaryColor,
                      foregroundColor: Colors.white,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                    ),
                  ),
                ),
              ]),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTextField({
    required TextEditingController controller,
    required String label,
    required IconData icon,
    bool mandatory = true,
  }) {
    return TextFormField(
      controller: controller,
      decoration: InputDecoration(
        labelText: label,
        prefixIcon: Icon(icon, color: _primaryColor),
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
      ),
      validator: mandatory
          ? (v) => (v == null || v.trim().isEmpty) ? 'Veuillez remplir ce champ' : null
          : null,
    );
  }

  String _bytesToHexString(dynamic data) {
    if (data == null) return '';
    try {
      if (data is String) return data;
      Uint8List bytes;
      if (data is Uint8List) {
        bytes = data;
      } else if (data is List<int>) {
        bytes = Uint8List.fromList(data);
      } else if (data is Iterable) {
        bytes = Uint8List.fromList(data.cast<int>().toList());
      } else {
        return data.toString();
      }

      return bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join('').toUpperCase();
    } catch (_) {
      return data.toString();
    }
  }

  String _bytesToUid(dynamic data) {
    final s = _bytesToHexString(data).trim();
    if (s.isEmpty) return '';
    return s.replaceAll('-', '').replaceAll(':', '').replaceAll(' ', '').toUpperCase();
  }
}
