import 'package:cheminova/provider/visit_pdrd_provider.dart';
import 'package:cheminova/widgets/common_drawer.dart';
import 'package:flutter/material.dart';
import 'package:cheminova/widgets/common_background.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../widgets/common_app_bar.dart';
import '../widgets/common_elevated_button.dart';
import '../widgets/common_text_form_field.dart';
import 'package:image_picker/image_picker.dart';

// Screen for visiting dealers and submitting visit details
class VisitDealersScreen extends StatefulWidget {
  final String? tradeName; // Name of the trade
  final String? id; // ID of the visit
  final String? type; // Type of the visit

  const VisitDealersScreen({super.key, required this.tradeName, this.id, this.type});

  @override
  State<VisitDealersScreen> createState() => VisitDealersScreenState();
}

class VisitDealersScreenState extends State<VisitDealersScreen> {
  late VisitPdRdProvider _visitPdRdProvider; // Provider for managing visit data
  final dateController = TextEditingController(
      text: DateFormat('dd/MM/yyyy').format(DateTime.now())); // Controller for date input

  final timeController =
  TextEditingController(text: DateFormat('hh:mm a').format(DateTime.now())); // Controller for time input

  final notesController = TextEditingController(); // Controller for notes
  final dealerController = TextEditingController(); // Controller for dealer input
  final meetingSummaryController = TextEditingController(); // Controller for meeting summary
  final followUpActionsController = TextEditingController(); // Controller for follow-up actions
  final nextVisitDateController = TextEditingController(); // Controller for next visit date
  late TextEditingController retailerController = TextEditingController(); // Controller for retailer input

  String selectedPurpose = 'Sales'; // Default selected purpose for the visit
  List<String> purposeOptions = ['Sales', 'Dues collection', 'Others']; // Options for visit purpose

  // Function to pick an image from the camera or gallery
  Future<void> _pickImage(ImageSource source) async {
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: source); // Pick image from specified source
    if (image != null) {
      // Handle the picked image
      print('Image picked: ${image.path}'); // Log the picked image path
      setState(() {
        notesController.text = image.path; // Update notes with image path
      });
    }
  }

  // Function to show action sheet for selecting image source
  void _showImageSourceActionSheet() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SafeArea(
          child: Wrap(
            children: <Widget>[
              ListTile(
                leading: const Icon(Icons.camera_alt), // Icon for camera
                title: const Text('Take a photo'), // Option to take a photo
                onTap: () {
                  Navigator.pop(context); // Close the bottom sheet
                  _pickImage(ImageSource.camera); // Pick image from camera
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo_library), // Icon for gallery
                title: const Text('Choose from gallery'), // Option to choose from gallery
                onTap: () {
                  Navigator.pop(context); // Close the bottom sheet
                  _pickImage(ImageSource.gallery); // Pick image from gallery
                },
              ),
            ],
          ),
        );
      },
    );
  }

  // Function to select the next visit date
  Future<void> _selectNextVisitDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: DateTime.now(), // Set initial date to today
      firstDate: DateTime.now(), // Allow selecting today or later
      lastDate: DateTime.now().add(const Duration(days: 365)), // Limit selection to one year from today
    );
    if (picked != null) {
      setState(() {
        nextVisitDateController.text = DateFormat('dd/MM/yyyy').format(picked); // Update controller with selected date
      });
    }
  }

  @override
  void initState() {
    _visitPdRdProvider = VisitPdRdProvider(); // Initialize provider
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    retailerController = TextEditingController(text: widget.tradeName); // Initialize retailer controller with trade name

    return ChangeNotifierProvider(
      create: (context) => _visitPdRdProvider, // Provide visit data to the widget tree
      child: CommonBackground(
        child: Stack(
          children: [
            Scaffold(
              backgroundColor: Colors.transparent,
              appBar: CommonAppBar(
                actions: [
                  IconButton(
                    onPressed: () {
                      Navigator.pop(context); // Back navigation
                    },
                    icon: Image.asset('assets/Back_attendance.png'),
                    padding: const EdgeInsets.only(right: 20),
                  ),
                ],
                title: Column(
                  children: [
                    const Text('Visit Retailers',
                        style: TextStyle(
                            fontSize: 20,
                            color: Colors.black,
                            fontWeight: FontWeight.w400,
                            fontFamily: 'Anek')),
                    Text(widget.tradeName ?? '', // Display trade name
                        style: const TextStyle(
                            fontSize: 20,
                            color: Colors.black,
                            fontWeight: FontWeight.w400,
                            fontFamily: 'Anek')),
                  ],
                ),
                backgroundColor: Colors.transparent,
                elevation: 0,
              ),
              drawer: const CommonDrawer(), // Drawer for navigation
              body: SingleChildScrollView(
                physics: const BouncingScrollPhysics(),
                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: 16.0),
                      decoration: BoxDecoration(
                          border: Border.all(color: Colors.white),
                          color: const Color(0xffB4D1E5).withOpacity(0.9),
                          borderRadius: BorderRadius.circular(26.0)),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          CommonTextFormField(
                              readOnly: true,
                              title: 'Select Retailer',
                              fillColor: Colors.white,
                              controller: retailerController), // Retailer selection field
                          const SizedBox(height: 15),
                          CommonTextFormField(
                              title: 'Visit date',
                              readOnly: true,
                              fillColor: Colors.white,
                              controller: dateController), // Date field
                          const SizedBox(height: 15),
                          CommonTextFormField(
                              title: 'Time',
                              readOnly: true,
                              fillColor: Colors.white,
                              controller: timeController), // Time field
                          const SizedBox(height: 15),
                          DropdownButtonFormField<String>(
                            decoration: const InputDecoration(
                              labelText: 'Purpose of visit',
                              fillColor: Colors.white,
                              filled: true,
                            ),
                            value: selectedPurpose, // Current selected purpose
                            items: purposeOptions.map((String value) {
                              return DropdownMenuItem<String>(
                                value: value,
                                child: Text(value),
                              );
                            }).toList(),
                            onChanged: (String? newValue) {
                              setState(() {
                                selectedPurpose = newValue!; // Update selected purpose
                              });
                            },
                          ),
                          const SizedBox(height: 15),
                          CommonTextFormField(
                              title: 'Meeting summary:',
                              fillColor: Colors.white,
                              maxLines: 3,
                              controller: meetingSummaryController), // Summary of the meeting
                          const SizedBox(height: 15),
                          CommonTextFormField(
                              title: 'Follow-up Actions:',
                              fillColor: Colors.white,
                              maxLines: 3,
                              controller: followUpActionsController), // Actions to follow up
                          const SizedBox(height: 15),
                          GestureDetector(
                            onTap: _selectNextVisitDate, // Handle date selection
                            child: AbsorbPointer(
                              child: CommonTextFormField(
                                title: 'Next visit date:',
                                readOnly: true,
                                fillColor: Colors.white,
                                controller: nextVisitDateController, // Next visit date field
                              ),
                            ),
                          ),
                          const SizedBox(height: 15),
                          Row(
                            children: [
                              Expanded(
                                child: CommonTextFormField(
                                    title: 'Attach Documents/Photos',
                                    fillColor: Colors.white,
                                    controller: notesController), // Notes for documents/photos
                              ),
                              IconButton(
                                icon: const Icon(Icons.add_a_photo),
                                onPressed: _showImageSourceActionSheet, // Open image source selection
                              ),
                            ],
                          ),
                          const SizedBox(height: 15),
                          Consumer<VisitPdRdProvider>(
                            builder: (context, value, child) => Align(
                              alignment: Alignment.center,
                              child: CommonElevatedButton(
                                borderRadius: 30,
                                width: double.infinity,
                                height: kToolbarHeight - 10,
                                text: 'SUBMIT', // Submit button
                                backgroundColor: const Color(0xff004791),
                                onPressed: () {
                                  // Submit visit details to provider
                                  value.submitVisitPdRd(
                                    widget.id ?? '',
                                    type: widget.type,
                                    retailerName: retailerController.text,
                                    visitDate: dateController.text,
                                    visitTime: timeController.text,
                                    note: meetingSummaryController.text,
                                    selectedPurpose: selectedPurpose,
                                    followUpActions: followUpActionsController.text,
                                    nextVisitDate: nextVisitDateController.text,
                                  );
                                },
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
            // Loading overlay
            Consumer<VisitPdRdProvider>(
              builder: (context, value, child) {
                if (value.isLoading) {
                  return Container(
                    color: Colors.black.withOpacity(0.5),
                    child: const Center(
                      child: CircularProgressIndicator(), // Loading indicator
                    ),
                  );
                }
                return const SizedBox.shrink(); // Return empty widget when not loading
              },
            ),
          ],
        ),
      ),
    );
  }
}
