import 'dart:async';

import 'package:flutter/material.dart';
import 'package:job_portal_app/Services/global_variables.dart';
import 'package:job_portal_app/UI/Company/company_home_screen.dart';
import 'package:job_portal_app/logic/fetch.dart';
import 'package:provider/provider.dart';

import '../../Services/Common/new_notification_manager.dart';
import '../../Services/Common/signalR.dart';
import '../../Widgets/consumer_widget.dart';

// ignore: camel_case_types
class CompanyMainScreen extends StatefulWidget {
  const CompanyMainScreen({super.key});

  @override
  State<CompanyMainScreen> createState() => _CompanyMainScreenState();
}

// ignore: camel_case_types
class _CompanyMainScreenState extends State<CompanyMainScreen> {
  late NewNotificationManager notificationManager = NewNotificationManager();
  signalR mysignalr = signalR();
  OverlayEntry? _overlayEntry;

  int y = 0;
  int x = 0;
  bool _new = false;

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

  Future<void> _myInitState() async {
    _new = await mysignalr.asyncInitState();
    if (_new == true) {
      setState(() {
        fetchData();
        _myInitState();
      });
    }
  }

  @override
  void dispose() {
    mysignalr.hubConnection.stop();
    _removeOverlay();

    super.dispose();
  }

  Future<void> fetchData() async {
    try {
      y = identifier.id;
      x = await fetch.getNumberOfCompanyNotifications(y);
      setState(() {
        notificationManager =
            Provider.of<NewNotificationManager>(context, listen: false);
        notificationManager.updateNotificationCount(x);
        _updateOverlay();
      });
    } catch (error) {
      // ignore: avoid_print
      print(error);
    }
  }

  void _updateOverlay() {
    if (_overlayEntry == null) {
      _overlayEntry = _createOverlayEntry();
      Overlay.of(context).insert(_overlayEntry!);
    } else {
      _overlayEntry?.markNeedsBuild();
    }
  }

  void _removeOverlay() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

  OverlayEntry _createOverlayEntry() {
    return OverlayEntry(
      builder: (context) =>
          const Positioned(bottom: 70, right: 15, child: ConsumerWidget()),
    );
  }

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: CompanyHomeScreen(),
      ),
    );
  }
}
