import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:bookatanker/common/settings.dart';
import 'package:bookatanker/models/supplier_tankers_model.dart';

class PlaceOrder extends StatefulWidget {
  var details;
  PlaceOrder({this.details});

  @override
  State<PlaceOrder> createState() => _PlaceOrderState();
}

class _PlaceOrderState extends State<PlaceOrder> {

  bool isTankerDataLoading = false;
  bool isSereverIssue = false;
  List<SupplierTankersModel> tankersList = [];
  String? _selectedOption = 'Yes';
  int quantity = 1;
  DateTime? _selectedDate;
  String displayDeliveryDate='';
  TimeOfDay? _selectedTime;
  TimeOfDay _selectedTime1 = TimeOfDay(hour: 9, minute: 0);

  Future<void> _pickTime() async {
    final TimeOfDay now = TimeOfDay.now();

    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: _selectedTime ?? now,
      helpText: 'Select a time',
    );

    if (picked != null && picked != _selectedTime) {
      setState(() {
        _selectedTime = picked;
      });
    }
  }

  void _showTimePicker() {
    showCupertinoModalPopup(
      context: context,
      builder: (_) => Container(
        height: 300,
        color: Colors.white,
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.all(16),
              child: Text(
                'Select Time',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
            ),
            Expanded(
              child: CupertinoDatePicker(
                mode: CupertinoDatePickerMode.time,
                use24hFormat: false, // true for 24-hour format
                initialDateTime: DateTime(
                  0,
                  0,
                  0,
                 /* _selectedTime!.hour,
                  _selectedTime!.minute,*/
                ),
                onDateTimeChanged: (DateTime newTime) {
                  setState(() {
                    _selectedTime = TimeOfDay(
                      hour: newTime.hour,
                      minute: newTime.minute,
                    );
                  });
                },
              ),
            ),
            CupertinoButton(
              child: Text('Done'),
              onPressed: () => Navigator.of(context).pop(),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _selectTime(BuildContext context) async {

    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: _selectedTime1,
      cancelText: 'Cancel',
      confirmText: 'Confirm',
      builder: (BuildContext context, Widget? child) {
        return Theme(
          data: ThemeData.dark().copyWith(
              primaryColor: Color(0XFF1D7AFC),
              timePickerTheme: TimePickerThemeData(
                backgroundColor: Colors.white,
                dialBackgroundColor: Colors.white,
                hourMinuteTextColor: Color(0XFF1D7AFC),
                dayPeriodTextColor: Color(0XFF1D7AFC),
                dialTextColor: Color(0XFF1D7AFC),
                dayPeriodColor: Color(0XFFC3C4C4),
                hourMinuteShape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20),
                  side: BorderSide(color: Color(0XFFFFFFFF), width: 2),
                ),
                dayPeriodShape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                dialHandColor: Color(0XFFC3C4C4),
                hourMinuteColor: Color(0XFFFFFFFF),
                dialTextStyle: fontTextStyle(14, Color(0XFF1D7AFC), FontWeight.w600),
                dayPeriodTextStyle: fontTextStyle(14, Color(0XFF1D7AFC), FontWeight.w600),
                hourMinuteTextStyle: fontTextStyle(50, Color(0XFF1D7AFC), FontWeight.w600),
                helpTextStyle: fontTextStyle(14, Color(0XFF1D7AFC), FontWeight.w600),
                cancelButtonStyle: ButtonStyle(
                  foregroundColor: MaterialStateProperty.all<Color>(Color(0XFF1D7AFC)),
                  padding: MaterialStateProperty.all<EdgeInsets>(EdgeInsets.symmetric(horizontal: 20, vertical: 10)),
                  textStyle: MaterialStateProperty.all<TextStyle>(fontTextStyle(14, Colors.white, FontWeight.w600)),
                ),
                confirmButtonStyle: ButtonStyle(
                  foregroundColor: MaterialStateProperty.all<Color>(Color(0XFF1D7AFC)),
                  padding: MaterialStateProperty.all<EdgeInsets>(EdgeInsets.symmetric(horizontal: 20, vertical: 10)),
                  textStyle: MaterialStateProperty.all<TextStyle>(fontTextStyle(14, Colors.white, FontWeight.w600)),
                ),
              )),
          child: child!,
        );
      },
    );

    if (picked != null && picked != _selectedTime) {
      setState(() {
        _selectedTime = picked;
      });
    }
  }

  Future<void> _pickDate() async {
    DateTime now = DateTime.now();
    DateTime lastDate = now.add(Duration(days: 15));

    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate ?? now,
      firstDate: now, // Restrict to today or later
      lastDate: lastDate, // Only allow next 15 days
      helpText: 'Select From Date',
      initialEntryMode: DatePickerEntryMode.calendarOnly,
      builder: (BuildContext context, Widget? child) {
        return Theme(
          data: ThemeData.light().copyWith(
            inputDecorationTheme: InputDecorationTheme(
              border: InputBorder.none, // Removes the text field border
            ),
            colorScheme: ColorScheme.light(
              primary: Color(0XFF1D7AFC),
              onPrimary: Color(0XFFFFFFFF), // Header text color
              surface: Color(0XFFFFFFFF),
              onSurface: Colors.black,
              secondary: Colors.pink,

            ),
            dividerColor: Color(0XFFF5F6F6),
            textButtonTheme: TextButtonThemeData(
              style: ButtonStyle(
                foregroundColor: MaterialStateProperty.all(Color(0XFF1D7AFC),), // Text color
                //backgroundColor: MaterialStateProperty.all(Colors.grey[200]), // Background
                textStyle: MaterialStateProperty.all(fontTextStyle(14, Color(0XFF1D7AFC), FontWeight.w600),), // Font style
                shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))), // Rounded corners
              ),
              // Background of the dialog box
            ),
            textTheme: TextTheme(
              bodyLarge: fontTextStyle(14, Color(0XFF1D7AFC), FontWeight.w600),
              labelLarge: fontTextStyle(14, Color(0XFF1D7AFC), FontWeight.w600),
              titleLarge:  fontTextStyle(14, Color(0XFF1D7AFC), FontWeight.w600),
              headlineLarge: fontTextStyle(20, Color(0XFF1D7AFC), FontWeight.w600),

            ),

          ),
          child: child!,
        );
      },
    );

    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
        //apiFromDate = DateFormat('dd-MMM-yyyy - 23:50').format(_selectedDate!);
        String from=DateFormat('dd-MMM-yyyy - HH:mm').format(_selectedDate!);
        DateTime parsedFromDate = DateFormat('dd-MMM-yyyy - HH:mm').parse(from);
        String formattedFromDate = DateFormat('dd MMM yyyy').format(parsedFromDate);
        displayDeliveryDate = formattedFromDate;
      });
    }
  }

  Future<void> getTankers() async {
    isTankerDataLoading = true;
    try {
      var tankerResponse = await AppSettings.getAllTankers(widget.details.supplier_id);

      setState(() {
        tankersList =
            ((jsonDecode(tankerResponse)['data']) as List).map((dynamic model) {
              return SupplierTankersModel.fromJson(model);
            }).toList();



        isTankerDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isTankerDataLoading = false;
        isSereverIssue = true;
      });
      /* AppSettings.longFailedToast('There is an issue at server side please try after some time');
      Navigator.pop(context);*/
    }
  }


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getTankers();
  }

  void increment() {
    setState(() {
      quantity++;
    });
  }

  void decrement() {
    setState(() {
      if (quantity > 1) quantity--;
    });
  }

  Widget renderUi(){
    Map<String, List<SupplierTankersModel>> groupByType(List<SupplierTankersModel> items) {
      final Map<String, List<SupplierTankersModel>> grouped = {};
      for (var item in items) {
        grouped.putIfAbsent(item.type_of_water, () => []).add(item);
      }
      return grouped;
    }
    final groupedData = groupByType(tankersList);

    if(tankersList.isNotEmpty){
      return Padding(padding: EdgeInsets.fromLTRB(12, 8, 12, 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          // 🔹 Supplier Name
          SizedBox(height: MediaQuery.of(context).size.height * .016),
          Text(
            widget.details.supplier_name,
            style: fontTextStyle(16, Color(0XFF2D2E30), FontWeight.w600),
          ),
          SizedBox(height: MediaQuery.of(context).size.height * .020),

          // 🔹 Grouped Items
          ...groupedData.entries.map((entry) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(entry.key,
                    style: fontTextStyle(12, Color(0XFF232527), FontWeight.w500)),
                SizedBox(height: MediaQuery.of(context).size.height * .020),
                Wrap(
                  spacing: 8,
                  runSpacing: 8,
                  children: entry.value.map((item) {
                    return Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                      decoration: BoxDecoration(
                        color: item.isStrikethrough
                            ? Colors.black87
                            : item.isSelected
                            ? Colors.black
                            : Colors.transparent,
                        border: Border.all(
                          color: item.isSelected
                              ? Colors.orange
                              : Colors.grey.shade400,
                        ),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      child: Text(
                        item.capacity + ' L',
                        style: TextStyle(
                          color: item.isStrikethrough ? Colors.white : Colors.black,
                          decoration: item.isStrikethrough
                              ? TextDecoration.lineThrough
                              : TextDecoration.none,
                        ),
                      ),
                    );
                  }).toList(),
                ),
                SizedBox(height: MediaQuery.of(context).size.height * .020),
                Divider(color: Colors.grey.shade300,),
              ],
            );
          }).toList(),
          SizedBox(height: MediaQuery.of(context).size.height * .016),
          // 🔹 Quantity Row: Comes immediately after list
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Quantity',
                style: fontTextStyle(12, Color(0XFF232527), FontWeight.w500),
              ),
              Row(
                children: [
                  GestureDetector(
                    onTap: () {
                      decrement();
                    },
                    child: Container(
                      width: 24,
                      height: 24,
                      decoration: BoxDecoration(
                        color: Color(0XFFC9DFFE),
                        shape: BoxShape.circle,
                      ),
                      child: Center(
                        child: Image.asset(
                          'images/minus.png',
                          width: 12,
                          height: 12,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: MediaQuery.of(context).size.width * .008),
                  Text(
                   quantity.toString(),
                    style: fontTextStyle(12, Color(0XFF000000), FontWeight.w400),
                  ),
                  SizedBox(width: MediaQuery.of(context).size.width * .008),
                  GestureDetector(
                    onTap: () {
                      increment();
                    },
                    child: Container(
                      width: 24,
                      height: 24,
                      decoration: BoxDecoration(
                        color: Color(0XFFC9DFFE),
                        shape: BoxShape.circle,
                      ),
                      child: Center(
                        child: Image.asset(
                          'images/plus.png',
                          width: 12,
                          height: 12,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
          SizedBox(height: MediaQuery.of(context).size.height * .016),
          Divider(color: Colors.grey.shade300,),
          SizedBox(height: MediaQuery.of(context).size.height * .016),
          Text(
            'Pump',
            style: fontTextStyle(12, Color(0XFF232527), FontWeight.w500),
          ),
          SizedBox(height: MediaQuery.of(context).size.height * .004),
          Row(
            children: [
              Row(
                children: [
                  Radio<String>(
                    value: 'Yes',
                    groupValue: _selectedOption,
                    activeColor: primaryColor,
                    visualDensity: VisualDensity.compact,
                    materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    onChanged: (value) {
                      setState(() {
                        _selectedOption = value;
                      });
                    },
                  ),
                  Text('Yes',style: fontTextStyle(12, Color(0XFF2D2E30), FontWeight.w500),),
                ],
              ),
              SizedBox(width: MediaQuery.of(context).size.width * .040),
              Row(
                children: [
                  Radio<String>(
                    value: 'No',
                    groupValue: _selectedOption,
                    activeColor: primaryColor,
                    visualDensity: VisualDensity.compact,
                    materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    onChanged: (value) {
                      setState(() {
                        _selectedOption = value;
                      });
                    },
                  ),
                  Text('No',style: fontTextStyle(12, Color(0XFF2D2E30), FontWeight.w500),),
                ],
              ),
            ],
          ),
          SizedBox(height: MediaQuery.of(context).size.height * .016),
          Divider(color: Colors.grey.shade300,),
          SizedBox(height: MediaQuery.of(context).size.height * .016),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Date of delivery',
                style: fontTextStyle(12, Color(0XFF232527), FontWeight.w500),
              ),
              Row(
                children: [
                  Container(
                    decoration: BoxDecoration(
                        shape: BoxShape.rectangle,
                        color: Color(0XFFF6F6F6),
                        border: Border.all(
                          width: 1,
                          color: Color(0XFFF6F6F6),
                        ),
                        borderRadius:
                        BorderRadius.circular(
                          5,
                        )),
                    padding: EdgeInsets.fromLTRB(4, 4, 4,4),
                    child: Text(
                      displayDeliveryDate.toString(),
                      style: fontTextStyle(12, Color(0XFF646566), FontWeight.w500),
                    ),
                  ),
                  SizedBox(width: MediaQuery.of(context).size.width * .032),
                  GestureDetector(
                    onTap: () {
                      _pickDate();
                    },
                    child: Image.asset(
                      'images/calender.png',
                      width: 20,
                      height: 20,
                    ),
                  ),
                ],
              ),
            ],
          ),
          SizedBox(height: MediaQuery.of(context).size.height * .016),
          Divider(color: Colors.grey.shade300,),
          SizedBox(height: MediaQuery.of(context).size.height * .016),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Time of delivery',
                style: fontTextStyle(12, Color(0XFF232527), FontWeight.w500),
              ),
              Row(
                children: [
                  Container(
                    decoration: BoxDecoration(
                        shape: BoxShape.rectangle,
                        color: Color(0XFFF6F6F6),
                        border: Border.all(
                          width: 1,
                          color: Color(0XFFF6F6F6),
                        ),
                        borderRadius:
                        BorderRadius.circular(
                          5,
                        )),
                    padding: EdgeInsets.fromLTRB(4, 4, 4,4),
                    child: Text(
                      _selectedTime1.format(context),
                      style: fontTextStyle(12, Color(0XFF646566), FontWeight.w500),
                    ),
                  ),

                  SizedBox(width: MediaQuery.of(context).size.width * .032),
                  GestureDetector(
                    onTap: () {
                      //_pickTime();
                      //_showTimePicker();
                      _selectTime(context);
                    },
                    child: Image.asset(
                      'images/clock.png',
                      width: 20,
                      height: 20,
                    ),
                  ),
                ],
              ),
            ],
          ),
          SizedBox(height: MediaQuery.of(context).size.height * .016),
          Row(
            children: [
              GestureDetector(
                onTap: () {},
                child: Image.asset(
                  'images/add_icon.png',
                  width: 24,
                  height: 24,
                ),
              ),
              SizedBox(width: MediaQuery.of(context).size.width * .032),
              Text(
                'Add order',
                style: fontTextStyle(12, Color(0XFF232527), FontWeight.w500),
              ),
            ],
          ),
          SizedBox(height: MediaQuery.of(context).size.height * .016),
          Row(
            mainAxisAlignment:
            MainAxisAlignment.spaceBetween,
            crossAxisAlignment:
            CrossAxisAlignment.start,
            children: [
              Expanded(child: GestureDetector(
                onTap: () {},
                child: Container(
                  decoration: BoxDecoration(
                      shape: BoxShape.rectangle,
                      color: Color(0XFFFFFFFF),
                      border: Border.all(
                        width: 1,
                        color: Color(0XFF1D7AFC),
                      ),
                      borderRadius:
                      BorderRadius.circular(
                        12,
                      )),
                  alignment: Alignment.center,
                  child: Padding(
                    padding: EdgeInsets.fromLTRB(
                        16, 12, 16, 12),
                    child: Text('SAVE DRAFT',
                        style: fontTextStyle(
                            12,
                            Color(0XFF1D7AFC),
                            FontWeight.w600)),
                  ),
                ),
              ),),
              SizedBox(
                width: MediaQuery.of(context)
                    .size
                    .width *
                    .032,
              ),
              Expanded(child: GestureDetector(
                onTap: () {
                  /*Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => PlaceOrder(details: connectedSuppliersList[index],)),
                          );*/
                },
                child: Container(
                  decoration: BoxDecoration(
                      shape: BoxShape.rectangle,
                      color: Color(0XFF1D7AFC),
                      border: Border.all(
                        width: 1,
                        color: Color(0XFFFFFFFF),
                      ),
                      borderRadius:
                      BorderRadius.circular(
                        12,
                      )),
                  alignment: Alignment.center,
                  child: Padding(
                    padding: EdgeInsets.fromLTRB(
                        16, 12, 16, 12),
                    child: Text('CONTINUE',
                        style: fontTextStyle(
                            12,
                            Color(0XFFFFFFFF),
                            FontWeight.w600)),
                  ),
                ),
              ))
            ],
          )
        ],
      ),
      );
    }

    else{
      return  Center(
        child: Text(
          'No Data Available',
          style: fontTextStyle(
              12, Color(0XFF000000), FontWeight.w500),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      backgroundColor:  Color(0XFFFFFFFF),
      appBar:  AppBar(
        backgroundColor: Colors.white,
        title: Text(
          'Place Order',
          style: fontTextStyle(14, Color(0XFF2A2A2A), FontWeight.w500),
        ),
        iconTheme: IconThemeData(color: Color(0XFF2A2A2A)),
        actions: [
          Row(
            children: [
              Padding(
                padding: EdgeInsets.fromLTRB(10, 10, 0, 10),
                child: IconButton(
                  icon: Image(
                      image: AssetImage(
                          'images/calender_supplier_landing.png')),
                  onPressed: () {},
                ),
              ),
              Padding(
                padding: EdgeInsets.fromLTRB(0, 10, 10, 10),
                child: IconButton(
                  icon: Image.asset(
                    'images/notification_appbar.png', // Example URL image
                  ),
                  onPressed: () {},
                ),
              )
            ],
          )
        ],
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Padding(
            padding: const EdgeInsets.fromLTRB(
                8, 8, 8, 8), // Add padding if needed
            child: Image.asset(
              'images/backbutton_appbar.png', // Replace with your image path
              fit: BoxFit.contain, // Adjust the fit
            ),
          ),
        ),
      ),
      body: isTankerDataLoading
          ? Center(
        child: CircularProgressIndicator(
          color: primaryColor,
          strokeWidth: 5.0,
        ),
      )
          : renderUi(),
    );
  }
}
