import 'package:cheminova/models/task_model.dart';
import 'package:cheminova/provider/task_provider.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:table_calendar/table_calendar.dart';
import '../widgets/common_app_bar.dart';
import '../widgets/common_background.dart';
import '../widgets/common_drawer.dart';

DateTime _focusedDay = DateTime.now();
DateTime _selectedDay = DateTime.now();

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

  @override
  State<CalendarScreen> createState() => _CalendarScreenState();
}

class _CalendarScreenState extends State<CalendarScreen> {
  late TaskProvider taskProvider;

  @override
  void initState() {
    taskProvider = TaskProvider();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => taskProvider,
      child: Consumer<TaskProvider>(
        builder: (context, value, child) => CommonBackground(
          child: Scaffold(
            appBar: CommonAppBar(
              actions: [
                IconButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  icon: Image.asset('assets/Back_attendance.png'),
                  padding: const EdgeInsets.only(right: 20),
                ),
              ],
              title: const Text('Calendar'),
              backgroundColor: Colors.transparent,
              elevation: 0,
            ),
            backgroundColor: Colors.transparent,
            drawer: const CommonDrawer(),
            body: Stack(
              children: [
                Column(children: [
                  const CalendarWidget(),
                  TaskList(taskProvider: value)
                ]),
                if (taskProvider.isLoading)
                  Container(
                    height: MediaQuery.of(context).size.height,
                    width: MediaQuery.of(context).size.width,
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.2),
                    ),
                    child: const Center(
                      child: CircularProgressIndicator(),
                    ),
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

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

  @override
  State<CalendarWidget> createState() => _CalendarWidgetState();
}

class _CalendarWidgetState extends State<CalendarWidget> {
  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.all(16),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: TableCalendar(
          firstDay: DateTime.utc(1900, 5, 1),
          lastDay: DateTime.utc(2900, 5, 1),
          focusedDay: _focusedDay,
          selectedDayPredicate: (day) {
            return isSameDay(_selectedDay, day);
          },
          onDaySelected: (selectedDay, focusedDay) {
            setState(() {
              _selectedDay = selectedDay;
              _focusedDay = focusedDay;
              context.read<TaskProvider>().getAllTaskByDate(_selectedDay);
            });
          },
          onPageChanged: (focusedDay) {
            _focusedDay = focusedDay;
          },
        ),
      ),
    );
  }
}

class TaskList extends StatefulWidget {
  final TaskProvider taskProvider;

  const TaskList({super.key, required this.taskProvider});

  @override
  State<TaskList> createState() => _TaskListState();
}

class _TaskListState extends State<TaskList> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      widget.taskProvider.getAllTaskByDate(_selectedDay);
    });
  }

  @override
  Widget build(BuildContext context) {
    return (widget.taskProvider.taskModelList.isEmpty)
        ? Container(
            alignment: Alignment.center,
            child: const Text('No task found',
                style: TextStyle(fontSize: 20, color: Colors.white)),
          )
        : Expanded(
            child: ListView.builder(
              itemCount: widget.taskProvider.taskModelList.length,
              itemBuilder: (context, index) {
                return _taskView(
                    task: widget.taskProvider.taskModelList[index]);
              },
            ),
          );
  }

  Widget _customContainer({required Widget child}) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.all(12.0),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.white),
          color: const Color(0xffB4D1E5).withOpacity(0.8),
          borderRadius: BorderRadius.circular(16.0),
        ),
        child: child,
      ),
    );
  }

  Widget _taskView({required TaskModel task}) {
    final formattedDate = DateFormat('dd/MM/yyyy').format(task.taskDueDate);
    return Column(
      children: [
        _customContainer(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "Assigned by: ${task.taskAssignedBy!.name}",
                style: const TextStyle(
                  fontFamily: 'Anek',
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 5),
              Text(
                "Task: ${task.task}",
                style: const TextStyle(
                  fontFamily: 'Anek',
                ),
              ),
              const SizedBox(height: 5),
              if (task.addedFor != null) ...{
                task.addedFor == 'PrincipalDistributor'
                    ? Text("PD: ${task.tradename}")
                    : Text("RD: ${task.tradename}"),
                const SizedBox(height: 5),
              },
              Text(
                'Status: ${task.taskStatus}',
                style: const TextStyle(
                  fontFamily: 'Anek',
                ),
              ),
              const SizedBox(height: 5),
              if (task.note != null) ...{
                Text(
                  'Note: ${task.note}',
                  style: const TextStyle(
                    fontFamily: 'Anek',
                  ),
                ),
                const SizedBox(height: 5),
              },
              Text(
                'Deadline: $formattedDate',
                style: const TextStyle(
                  fontFamily: 'Anek',
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 10),
      ],
    );
  }
}
