import 'package:flutter/material.dart';
import 'package:nfc_google_sheet/components/studentForm.dart';
import 'package:nfc_google_sheet/components/title.dart';
import 'package:flutter_nfc_kit/flutter_nfc_kit.dart';
import 'package:nfc_google_sheet/context/colories.dart';
import 'package:nfc_google_sheet/database/databaseHelper.dart';

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return MyHomePage();
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String nfcData = "Appuyez sur une carte NFC";
  ScanStatus _scanStatus = ScanStatus.idle;

  Future<void> startNFC() async {
    try {
      var availability = await FlutterNfcKit.nfcAvailability;
      if (availability != NFCAvailability.available) {
        setState(() {
          nfcData = "NFC non disponible ou désactivé.";
          _scanStatus = ScanStatus.error;
        });
        return;
      }

      setState(() {
        nfcData = "En attente d'une carte NFC...";
        _scanStatus = ScanStatus.scanning;
      });

      NFCTag tag = await FlutterNfcKit.poll(timeout: Duration(seconds: 15));
      final cardId = tag.id;

      List<Map<String, dynamic>> users = await DatabaseHelper.instance.queryAllUsers();
      bool userExists = users.any((user) => user['cardId'] == cardId);

      if (userExists) {
        setState(() {
          nfcData = "Utilisateur déjà inscrit";
          _scanStatus = ScanStatus.error;
        });
      } else {
        setState(() {
          nfcData = "ID de la carte NFC: $cardId";
          _scanStatus = ScanStatus.success;
        });
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return StudentForm(cardId: cardId);
          },
        );
      }
    } catch (e) {
      setState(() {
        nfcData = "Erreur ou scan annulé.";
        _scanStatus = ScanStatus.error;
      });
    } finally {
      await FlutterNfcKit.finish();
      if (_scanStatus == ScanStatus.scanning) {
        setState(() {
          _scanStatus = ScanStatus.idle;
          nfcData = "Appuyez sur une carte NFC";
        });
      }
    }
  }

  Widget _buildStatusIcon() {
    switch (_scanStatus) {
      case ScanStatus.scanning:
        return SizedBox(
          width: 120,
          height: 120,
          child: CircularProgressIndicator(
            color: Colories.selected,
            strokeWidth: 6,
          ),
        );
      case ScanStatus.success:
        return Icon(
          Icons.check_circle_outline,
          color: Colories.selected,
          size: 120,
        );
      case ScanStatus.error:
        return Icon(
          Icons.error_outline,
          color: Colors.red.shade400,
          size: 120,
        );
      default:
        return Icon(
          Icons.nfc,
          color: Colories.unselected.withValues(alpha: 0.7),
          size: 120,
        );
    }
  }

  Widget _buildStatusText() {
    Color textColor;
    switch (_scanStatus) {
      case ScanStatus.success:
        textColor = Colories.selected;
        break;
      case ScanStatus.error:
        textColor = Colors.red.shade400;
        break;
      default:
        textColor = Colories.unselected;
    }

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: Colories.subtitle.withValues(alpha: 0.5),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Text(
        nfcData,
        textAlign: TextAlign.center,
        style: TextStyle(
          color: textColor,
          fontSize: 16,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    bool isScanning = _scanStatus == ScanStatus.scanning;

    return Scaffold(
      backgroundColor: Colories.background,
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Column(
            children: [
              TitleCustom(content: 'ENREGISTREZ - VOUS'),
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    _buildStatusIcon(),
                    SizedBox(height: 30),
                    _buildStatusText(),
                  ],
                ),
              ),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton.icon(
                  onPressed: isScanning ? null : startNFC,
                  icon: Icon(
                    Icons.nfc,
                    color: Colories.background,
                  ),
                  label: Text(
                    isScanning ? "SCAN EN COURS..." : "ENREGISTRER SA CARTE",
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      letterSpacing: 1.1,
                    ),
                  ),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colories.selected,
                    foregroundColor: Colories.background,
                    disabledBackgroundColor: Colories.selected.withValues(alpha: 0.5),
                    padding: EdgeInsets.symmetric(vertical: 18),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

enum ScanStatus {
  idle,
  scanning,
  success,
  error,
}