import 'package:cheminova/models/Daily_Task_Response.dart';
import 'package:cheminova/screens/Add_products_screen.dart';
import 'package:cheminova/screens/add_sales_product_screen.dart';
import 'package:cheminova/screens/collect_kyc_screen.dart';
import 'package:cheminova/screens/visit_rd_pd_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:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

import '../provider/daily_task_provider.dart';

/// This widget represents the Daily Tasks screen which is
/// divided into three categories: New, Pending, and Completed.
class DailyTasksScreen extends StatefulWidget {
  const DailyTasksScreen({super.key});

  @override
  State<DailyTasksScreen> createState() => _DailyTasksScreenState();
}

class _DailyTasksScreenState extends State<DailyTasksScreen> {
  final List<String> _tabTitles = ['NEW', 'PENDING', 'COMPLETED']; // Tab labels
  int _selectedTabIndex = 0; // Current selected tab index
  late DailyTaskProvider _dailyTaskProvider;

  /// Initial setup for getting the initial data (New tasks).
  @override
  void initState() {
    _dailyTaskProvider = DailyTaskProvider();
    _dailyTaskProvider.getTask(type: 'New');
    super.initState();
  }

  /// The build function returns the widget tree for the DailyTasksScreen.
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
        create: (context) => _dailyTaskProvider,
        child: Scaffold(
          extendBodyBehindAppBar: true,
          appBar: _buildAppBar(),
          drawer: const CommonDrawer(),
          body: CommonBackground(
            child: SafeArea(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildCustomTabBar(), // Custom tab bar for task categories
                  Expanded(
                    child: _buildTaskList(_selectedTabIndex), // Task list view based on selected tab
                  ),
                ],
              ),
            ),
          ),
        ));
  }

  /// Builds the app bar with a back button and the title 'Daily Tasks'.
  CommonAppBar _buildAppBar() {
    return CommonAppBar(
      backgroundColor: Colors.transparent,
      elevation: 0,
      actions: [
        IconButton(
          onPressed: () => Navigator.pop(context),
          icon: Image.asset('assets/Back_attendance.png'),
          padding: const EdgeInsets.only(right: 20),
        ),
      ],
      title: const Text(
        'Daily Tasks',
        style: TextStyle(color: Colors.black87, fontSize: 20),
      ),
    );
  }

  /// Custom tab bar at the top of the screen to switch between task categories.
  Widget _buildCustomTabBar() {
    return Container(
      height: 60,
      margin: const EdgeInsets.symmetric(vertical: 16, horizontal: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: List.generate(_tabTitles.length, (index) {
          return GestureDetector(
            onTap: () {
              // Update selected tab index and fetch relevant task data
              setState(() => _selectedTabIndex = index);
              if (index == 0) {
                _dailyTaskProvider.getTask(type: 'New');
              } else if (index == 1) {
                _dailyTaskProvider.getTask(type: 'Pending');
              } else {
                _dailyTaskProvider.getTask(type: 'Completed');
              }
            },
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: BoxDecoration(
                gradient: _selectedTabIndex == index
                    ? const LinearGradient(
                  colors: [Color(0xff004791), Color(0xff1a73e8)],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                )
                    : null,
                color: _selectedTabIndex == index
                    ? Colors.transparent
                    : Colors.white,
                borderRadius: BorderRadius.circular(10),
                border: Border.all(color: Colors.black),
                boxShadow: [
                  if (_selectedTabIndex == index)
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 6,
                      offset: const Offset(0, 4),
                    ),
                ],
              ),
              child: Row(
                children: [
                  Icon(
                    _getTabIcon(index),
                    color: _selectedTabIndex == index
                        ? Colors.white
                        : Colors.black,
                  ),
                  const SizedBox(width: 8),
                  Text(
                    _tabTitles[index],
                    style: TextStyle(
                      color: _selectedTabIndex == index
                          ? Colors.white
                          : Colors.black,
                      fontWeight: _selectedTabIndex == index
                          ? FontWeight.bold
                          : FontWeight.normal,
                    ),
                  ),
                ],
              ),
            ),
          );
        }),
      ),
    );
  }

  /// Provides appropriate icons for the tabs.
  IconData _getTabIcon(int index) {
    switch (index) {
      case 0:
        return Icons.new_releases;
      case 1:
        return Icons.pending;
      case 2:
        return Icons.check_circle;
      default:
        return Icons.new_releases;
    }
  }

  /// Builds the task list according to the selected tab.
  Widget _buildTaskList(int tabIndex) {
    return Consumer<DailyTaskProvider>(
      builder: (context, value, child) => value.isLoading
          ? const Center(child: CircularProgressIndicator())
          : ListView.separated(
        padding: const EdgeInsets.all(16),
        itemCount: _selectedTabIndex == 0
            ? value.newTasksList.length
            : _selectedTabIndex == 1
            ? value.pendingTasksList.length
            : value.completedTasksList.length,
        separatorBuilder: (context, index) => const SizedBox(height: 8),
        itemBuilder: (context, index) {
          final tasksList = tabIndex == 0
              ? value.newTasksList
              : tabIndex == 1
              ? value.pendingTasksList
              : value.completedTasksList;
          return _buildTaskCard(tasksList[index]);
        },
      ),
    );
  }

  /// Builds a task card widget based on the task details.
  Widget _buildTaskCard(Tasks tasksList) {
    return InkWell(
      onTap: _selectedTabIndex == 2
          ? null // Disable click when on the "COMPLETED" tab
          : () {
        print('Task: ${tasksList.toJson()}');
        // Navigation to respective screens based on task type
        if (tasksList.task == 'Collect KYC') {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) =>
                      CollectKycScreen(id: tasksList.sId ?? '')));
        } else if (tasksList.task == 'REUPLOAD') {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) =>
                      CollectKycScreen(id: tasksList.taskId ?? '')));
        } else if (tasksList.task == 'Update Inventory Data') {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => AddProductsScreen(
                      distributorType: tasksList.addedFor!,
                      tradeName: tasksList.tradeName ?? '',
                      pdRdId: tasksList.addedForId!,
                      inventoryId: tasksList.sId)));
        } else if (tasksList.task == 'Update Sales Data') {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => AddSalesProductScreen(
                    distributorType: tasksList.addedFor!,
                    tradeName: tasksList.tradeName!,
                    pdRdId: tasksList.addedForId!,
                    inventoryId: tasksList.sId,
                  )));
        } else if (tasksList.task == 'Visit RD/PD') {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => VisitDealersScreen(
                    tradeName: tasksList.tradeName ?? '',
                    id: tasksList.sId,
                    type: tasksList.addedFor,
                  )));
        }
      },
      child: Card(
        color: Colors.white,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ListTile(
              leading: const Icon(Icons.task, color: Colors.blueAccent),
              title: Text(tasksList.task ?? '',
                  style: const TextStyle(
                      color: Colors.black87,
                      fontWeight: FontWeight.w700,
                      fontSize: 16,
                      fontFamily: 'Anek')),
              trailing: _selectedTabIndex == 2
                  ? null // Remove arrow icon in "COMPLETED" tab
                  : const Icon(Icons.arrow_forward_ios, color: Colors.black87),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if (tasksList.note != null) Text('Note: ${tasksList.note}'),
                  if (tasksList.addedFor != null)
                    Text('Distributor: ${tasksList.addedFor ?? ""}'),
                  if (tasksList.tradeName != null)
                    Text('Trade Name: ${tasksList.tradeName ?? ""}'),
                  if (tasksList.taskDueDate != null)
                    Text(
                        'Due Date: ${DateFormat('dd/MM/yyyy').format(DateTime.parse(tasksList.taskDueDate!))}'),
                  if (tasksList.taskPriority != null)
                    Text('Priority: ${tasksList.taskPriority}'),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
