import 'package:cheminova/provider/attendance_provider.dart';
import 'package:cheminova/screens/Attendance_success.dart';
import 'package:cheminova/screens/on_leave_screen.dart';
import 'package:cheminova/widgets/common_app_bar.dart';
import 'package:cheminova/widgets/common_background.dart';
import 'package:cheminova/widgets/common_drawer.dart';
import 'package:cheminova/widgets/common_elevated_button.dart';
import 'package:cheminova/widgets/common_text_form_field.dart';
import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

class MarkAttendanceScreen extends StatefulWidget {
  const MarkAttendanceScreen({super.key});

  @override
  State<MarkAttendanceScreen> createState() => _MarkAttendanceScreenState(); // Create state for the screen
}

class _MarkAttendanceScreenState extends State<MarkAttendanceScreen> {
  late AttendanceProvider attendanceProvider; // Attendance provider instance
  final dateController = TextEditingController(
      text: DateFormat('yyyy/MM/dd').format(DateTime.now())); // Initialize date controller with the current date

  final timeController = TextEditingController(
      text: DateFormat('hh:mm a').format(DateTime.now())); // Initialize time controller with the current time

  final locationController = TextEditingController(); // Location controller for the user's current location
  final notesController = TextEditingController(); // Notes controller

  @override
  void initState() {
    super.initState();
    attendanceProvider = AttendanceProvider(); // Initialize the attendance provider
    _getCurrentLocation(); // Fetch the user's current location
  }

  Future<void> _getCurrentLocation() async {
    LocationPermission permission = await Geolocator.checkPermission(); // Check location permission
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission(); // Request permission if denied
      if (permission == LocationPermission.denied) {
        debugPrint('location denied'); // Log message if location permission is denied
        return;
      }
    }

    if (permission == LocationPermission.deniedForever) {
      setState(() {
        debugPrint('Location permissions are permanently denied'); // Log if permissions are permanently denied
      });
      return;
    }

    // Fetch user's current location with high accuracy
    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    debugPrint('position--- $position'); // Log position coordinates

    // Get the placemark (location information) from the coordinates
    List<Placemark> placeMarks = await placemarkFromCoordinates(
        position.latitude, position.longitude)
        .timeout(const Duration(seconds: 10)); // Set a timeout for location request
    debugPrint('place mark--- $placeMarks'); // Log the placemark details

    Placemark place = placeMarks[0]; // Use the first placemark
    setState(() {
      locationController.text = place.locality ?? ''; // Set locality to locationController
    });
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<AttendanceProvider>( // Provide attendance provider to widget tree
      create: (_) => attendanceProvider,
      builder: (context, child) => CommonBackground(
        child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: CommonAppBar(
            actions: [
              IconButton(
                onPressed: () {
                  Navigator.pop(context); // Go back when the button is pressed
                },
                icon: Image.asset('assets/Back_attendance.png'), // Back icon
                padding: const EdgeInsets.only(right: 20),
              ),
            ],
            title: const Text('Mark Attendance',
                style: TextStyle(
                    fontSize: 28,
                    color: Colors.black,
                    fontWeight: FontWeight.w400,
                    fontFamily: 'Anek')),
            backgroundColor: Colors.transparent,
            elevation: 0,
          ),
          drawer: const CommonDrawer(), // Common drawer
          body: Stack(
            children: [
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: SingleChildScrollView(
                  physics: const BouncingScrollPhysics(), // Smooth scrolling behavior
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      const SizedBox(height: 16),
                      Container(
                        padding: const EdgeInsets.all(20.0).copyWith(top: 30, bottom: 30),
                        margin: const EdgeInsets.symmetric(horizontal: 20.0),
                        decoration: BoxDecoration(
                            border: Border.all(color: Colors.white),
                            color: const Color(0xffB4D1E5).withOpacity(0.9),
                            borderRadius: BorderRadius.circular(26.0)), // Styling container
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            CommonTextFormField(
                                title: 'Date',
                                readOnly: true,
                                fillColor: Colors.white,
                                controller: dateController), // Date input field (read-only)
                            const SizedBox(height: 15),
                            CommonTextFormField(
                                title: 'Time',
                                readOnly: true,
                                fillColor: Colors.white,
                                controller: timeController), // Time input field (read-only)
                            const SizedBox(height: 15),
                            CommonTextFormField(
                                title: 'Location',
                                readOnly: true,
                                fillColor: Colors.white,
                                controller: locationController), // Location input field (read-only)
                            const SizedBox(height: 15),
                            CommonTextFormField(
                                height: 100,
                                title: 'Notes',
                                fillColor: Colors.white,
                                maxLines: 4,
                                controller: notesController), // Notes input field (editable)
                            const SizedBox(height: 16),
                            Align(
                              alignment: Alignment.center,
                              child: Column(
                                children: [
                                  Consumer<AttendanceProvider>(
                                    builder: (BuildContext context,
                                        AttendanceProvider value,
                                        Widget? child) =>
                                        CommonElevatedButton(
                                            backgroundColor: const Color(0xff004791),
                                            borderRadius: 30,
                                            width: double.infinity,
                                            height: kToolbarHeight - 10,
                                            text: 'MARK ATTENDANCE',
                                            onPressed: () {
                                              value
                                                  .markAttendance(
                                                  dateController.text.trim(), // Pass date
                                                  timeController.text.trim(), // Pass time
                                                  locationController.text.trim(), // Pass location
                                                  notesController.text.trim()) // Pass notes
                                                  .then(
                                                    (result) {
                                                  var (status, message) = result; // Destructure the result
                                                  ScaffoldMessenger.of(context)
                                                      .showSnackBar(SnackBar(
                                                      content: Text(message))); // Show a message based on the result
                                                  if (status) {
                                                    Navigator.pushReplacement(
                                                        context,
                                                        MaterialPageRoute(
                                                            builder: (context) =>
                                                            const AttendanceSuccess())); // Navigate to success screen on success
                                                  }
                                                },
                                              );
                                            }),
                                  ),
                                  const SizedBox(height: 15),
                                  CommonElevatedButton(
                                      borderRadius: 30,
                                      width: double.infinity,
                                      height: kToolbarHeight - 10,
                                      text: 'ON LEAVE',
                                      backgroundColor: const Color(0xff00784C),
                                      onPressed: () {
                                        Navigator.push(
                                            context,
                                            MaterialPageRoute(
                                              builder: (context) =>
                                              const OnLeaveScreen(), // Navigate to leave screen
                                            ));
                                      })
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Positioned(
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                child: Consumer<AttendanceProvider>(builder: (context, value, child) {
                  if (value.isLoading) { // Show loading indicator if loading
                    return Container(
                        color: Colors.black12,
                        child: const Center(child: CircularProgressIndicator()));
                  } else {
                    return const SizedBox(); // Return empty widget if not loading
                  }
                }),
              )
            ],
          ),
        ),
      ),
    );
  }
}
