import 'package:cheminova/screens/add_sales_product_screen.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:cheminova/models/Daily_Task_Response.dart';
import 'package:cheminova/widgets/common_app_bar.dart';
import 'package:cheminova/widgets/common_background.dart';
import 'package:cheminova/widgets/common_drawer.dart';
import '../constants/constant.dart';
import '../provider/daily_task_provider.dart';

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

  @override
  _SalesTaskScreenState createState() => _SalesTaskScreenState();
}

class _SalesTaskScreenState extends State<SalesTaskScreen> {
  late DailyTaskProvider _dailyTaskProvider;

  @override
  void initState() {
    super.initState();
    _dailyTaskProvider = DailyTaskProvider(); // Initialize the provider
    apiCall(); // Fetch tasks when the screen initializes
  }

  // Function to call API for fetching tasks
  void apiCall() async {
    await _dailyTaskProvider.getTask(type: 'New', isAddPending: true);
    await _dailyTaskProvider.getTask(type: 'Pending', isAddPending: true);
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => _dailyTaskProvider, // Provide the daily task provider
      child: Scaffold(
        extendBodyBehindAppBar: true,
        appBar: _buildAppBar(), // Build the app bar
        drawer: const CommonDrawer(), // Add a common drawer
        body: CommonBackground(
          child: SafeArea(
            child: _buildTaskList(), // Build the task list
          ),
        ),
      ),
    );
  }

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

  // Method to build the task list
  Widget _buildTaskList() {
    return Consumer<DailyTaskProvider>(
      builder: (context, value, child) {
        if (value.isLoading) {
          return const Center(child: CircularProgressIndicator()); // Loading indicator
        }

        // Filter sales tasks for "Update Sales Data"
        final salesTasks = value.newTasksList
            .where((task) =>
        task.task?.toLowerCase() == 'Update Sales Data'.toLowerCase())
            .toList();

        // If no tasks are found, display a message
        if (salesTasks.isEmpty) {
          return const Center(
            child: Text(
              'NO TASK',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
          );
        }

        // Build the list of tasks
        return ListView.separated(
          padding: const EdgeInsets.all(16),
          itemCount: salesTasks.length,
          separatorBuilder: (context, index) => const SizedBox(height: 8),
          itemBuilder: (context, index) => _buildTaskCard(salesTasks[index]), // Build each task card
        );
      },
    );
  }

  // Method to build individual task cards
  Widget _buildTaskCard(Tasks tasksList) {
    return InkWell(
      onTap: () {
        // Navigate to AddSalesProductScreen with the selected task details
        if (tasksList.sId != null && tasksList.addedFor != null) {
          Navigator.push(
              navigatorKey.currentContext!,
              MaterialPageRoute(
                  builder: (context) => AddSalesProductScreen(
                      distributorType: tasksList.addedFor!,
                      inventoryId: tasksList.sId,
                      tradeName: tasksList.tradeName ?? '',
                      pdRdId: tasksList.addedForId!)));
        }
      },
      child: Card(
        color: Colors.white,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        child: ListTile(
          leading: const Icon(Icons.attach_money, color: Colors.greenAccent), // Icon for the task
          title: Text(
            tasksList.task ?? '', // Task name
            style: const TextStyle(
              color: Colors.black87,
              fontWeight: FontWeight.w700,
              fontSize: 16,
              fontFamily: 'Anek',
            ),
          ),
          subtitle: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Distributor: ${tasksList.addedFor ?? ""}'), // Distributor information
              Text('Trader Name: ${tasksList.tradeName ?? ''}'), // Trader name
              if (tasksList.taskDueDate != null)
                Text(
                    'Due Date: ${DateFormat('dd/MM/yyyy').format(DateTime.parse(tasksList.taskDueDate!))}'), // Formatted due date
              Text('Priority: ${tasksList.taskPriority}'), // Task priority
            ],
          ),
          trailing: const Icon(Icons.arrow_forward_ios, color: Colors.black87), // Arrow icon for navigation
        ),
      ),
    );
  }
}
