import 'dart:convert';
import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:healthcare_pharmacy/models/pharmacy_accounts_model.dart';
import 'package:healthcare_pharmacy/settings.dart';


class PharmacyAccounts extends StatefulWidget {
  const PharmacyAccounts({Key? key}) : super(key: key);

  @override
  State<PharmacyAccounts> createState() => _PharmacyAccountsState();
}

class _PharmacyAccountsState extends State<PharmacyAccounts> {
  List<PharmacyAccountsModel> accountsList = [];
  String acceptedCount = '';
  String pendingRejectedCount = '';
  String deliveredCount = '';
  String deliveredTotalPrice = '';
  String deliveredTotalAmountPaid = '';
  String deliveredTotalAmountDue = '';

  bool isLoading = false;
  bool isSereverIssue = false;

  Future<void> readJson() async {
    isLoading = true;

    try {
      var pharmaResponse = await AppSettings.getPharmacyAccounts();
      print("pharmaResponse"+pharmaResponse);
      setState(() {
        accountsList =
            ((jsonDecode(pharmaResponse)['data']) as List).map((dynamic model) {
              return PharmacyAccountsModel.fromJson(model);
            }).toList();
        acceptedCount = jsonDecode(pharmaResponse)['acceptedCount'].toString();
        pendingRejectedCount =
            jsonDecode(pharmaResponse)['pendingRejectedCount'].toString();
        deliveredCount =
            jsonDecode(pharmaResponse)['deliveredCount'].toString();
        deliveredTotalPrice =
            jsonDecode(pharmaResponse)['deliveredTotalPrice'].toString();
        deliveredTotalAmountPaid =
            jsonDecode(pharmaResponse)['deliveredTotalAmountPaid'].toString();
        deliveredTotalAmountDue =
            jsonDecode(pharmaResponse)['deliveredTotalAmountDue'].toString();

        isLoading = false;
      });
    } catch (e) {
      setState(() {
        isLoading = false;
        isSereverIssue = true;
      });
    }
  }
  @override
  void initState() {
    // TODO: implement initState
    readJson();
    super.initState();
  }

  modelBottomSheet(var obj) {
    showModalBottomSheet<void>(
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(topLeft: Radius.circular(15.0), topRight: Radius.circular(15.0)),
      ),
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
            height: MediaQuery.of(context).size.height * .300,
            child: Padding(
              padding: EdgeInsets.all(10),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('Supplier Name', style: labelTextStyle()),
                      Text('Delivery Agent', style: labelTextStyle()),
                      Text('Tanker Name', style: labelTextStyle()),
                      Text('Capacity Of Tanker', style: labelTextStyle()),
                      Text('Booking Id', style: labelTextStyle()),
                      Text('Date Of Order', style: labelTextStyle()),
                      Text('Type Of Water', style: labelTextStyle()),
                      Text('Start Time', style: labelTextStyle()),
                      Text('Stop Time', style: labelTextStyle()),
                      Text('Initial Water Level', style: labelTextStyle()),
                      Text('Final Water Level', style: labelTextStyle()),
                      Text('Delivered Water', style: labelTextStyle()),
                      Text('Actual Price', style: labelTextStyle()),
                      Text('Amount Paid', style: labelTextStyle()),
                      Text('Amount Due', style: labelTextStyle()),
                      Text('Payment Mode', style: labelTextStyle()),
                    ],
                  ),
                  SizedBox(width:5),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(':', style: labelTextStyle()),
                      Text(':', style: labelTextStyle()),
                      Text(':', style: labelTextStyle()),
                      Text(':', style: labelTextStyle()),
                      Text(':', style: labelTextStyle()),
                      Text(':', style: labelTextStyle()),
                      Text(':', style: labelTextStyle()),
                      Text(':', style: labelTextStyle()),
                      Text(':', style: labelTextStyle()),
                      Text(':', style: labelTextStyle()),
                      Text(':', style: labelTextStyle()),
                      Text(':', style: labelTextStyle()),
                      Text(':', style: labelTextStyle()),
                      Text(':', style: labelTextStyle()),
                      Text(':', style: labelTextStyle()),
                      Text(':', style: labelTextStyle()),
                    ],
                  ),
                  SizedBox(width:5),
                  Expanded(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(obj.supplierName, style: valuesTextStyle()),
                        Text(obj.delivery_agent, style: valuesTextStyle()),
                        Text(obj.tanker_name, style: valuesTextStyle()),
                        Text(obj.capacity + ' Ltrs', style: valuesTextStyle()),
                        Text(obj.bookingid,
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                              overflow: TextOverflow.ellipsis,
                            )),
                        Text(obj.dateOfOrder,
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                              overflow: TextOverflow.ellipsis,
                            )),
                        Text(obj.typeofwater,
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                              overflow: TextOverflow.ellipsis,
                            )),
                        Text(obj.start_time,
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                              overflow: TextOverflow.ellipsis,
                            )),
                        Text(obj.stop_time,
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                              overflow: TextOverflow.ellipsis,
                            )),
                        Text(obj.initial_water_level + ' Ltrs',
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                              overflow: TextOverflow.ellipsis,
                            )),
                        Text(obj.final_water_level + ' Ltrs',
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                              overflow: TextOverflow.ellipsis,
                            )),
                        Text(obj.quantityDelivered + ' Ltrs',
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                              overflow: TextOverflow.ellipsis,
                            )),
                        Text(obj.price,
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                              overflow: TextOverflow.ellipsis,
                            )),
                        Text(obj.amount_paid,
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                              overflow: TextOverflow.ellipsis,
                            )),
                        Text(obj.amount_due,
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                              overflow: TextOverflow.ellipsis,
                            )),
                        Text(obj.payment_mode,
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                              overflow: TextOverflow.ellipsis,
                            )),
                      ],
                    ),
                  ),

                  Expanded(child: Column(
                    children: [
                      Icon(Icons.payment_outlined, color: obj.payment_color, size: 40,),
                      Text(obj.displayText,
                          style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                            overflow: TextOverflow.ellipsis,
                          )),
                    ],
                  ))
                ],
              ),
            ));
      },
    );
  }

  Widget _accounsList() {
    if (accountsList.length != 0) {
      return Column(crossAxisAlignment: CrossAxisAlignment.center, children: [
        Container(
            width: double.infinity,
            child: Padding(
              padding: EdgeInsets.fromLTRB(8, 8, 8, 0),
              child: Card(
                  child: Padding(
                      padding: EdgeInsets.all(8),
                      child: Row(
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                'acceptedCount',
                                style: labelTextStyle(),
                              ),
                              Text(
                                'pendingRejectedCount',
                                style: labelTextStyle(),
                              ),
                              Text(
                                'deliveredCount',
                                style: labelTextStyle(),
                              ),
                              Text(
                                'deliveredTotalPrice',
                                style: labelTextStyle(),
                              ),
                              Text(
                                'deliveredTotalAmountPaid',
                                style: labelTextStyle(),
                              ),
                              Text(
                                'deliveredTotalAmountDue',
                                style: labelTextStyle(),
                              ),
                            ],
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                ': ',
                                style: labelTextStyle(),
                              ),
                              Text(
                                ': ',
                                style: labelTextStyle(),
                              ),
                              Text(
                                ': ',
                                style: labelTextStyle(),
                              ),
                              Text(
                                ': ',
                                style: labelTextStyle(),
                              ),
                              Text(
                                ': ',
                                style: labelTextStyle(),
                              ),
                              Text(
                                ': ',
                                style: labelTextStyle(),
                              ),
                            ],
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                acceptedCount,
                                style: valuesTextStyle(),
                              ),
                              Text(
                                deliveredCount,
                                style: valuesTextStyle(),
                              ),
                              Text(
                                pendingRejectedCount,
                                style: valuesTextStyle(),
                              ),
                              Row(
                                children: [
                                  Icon(
                                    Icons.currency_rupee,
                                    color: Colors.black,
                                    size: 10,
                                  ),
                                  SizedBox(width: 5),
                                  Text(
                                    AppSettings.formNum(deliveredTotalPrice),
                                    style: valuesTextStyle(),
                                  ),
                                ],
                              ),
                              Row(
                                children: [
                                  Icon(
                                    Icons.currency_rupee,
                                    color: Colors.black,
                                    size: 10,
                                  ),
                                  SizedBox(width: 5),
                                  Text(
                                    AppSettings.formNum(
                                        deliveredTotalAmountPaid),
                                    style: valuesTextStyle(),
                                  ),
                                ],
                              ),
                              Row(
                                children: [
                                  Icon(
                                    Icons.currency_rupee,
                                    color: Colors.black,
                                    size: 10,
                                  ),
                                  SizedBox(width: 5),
                                  Text(deliveredTotalAmountDue=='null'?
                                  '':AppSettings.formNum(
                                      deliveredTotalAmountDue),
                                    style: valuesTextStyle(),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ))),
            )),
        Expanded(
            child: ListView.builder(
                padding: EdgeInsets.all(8),
                itemCount: accountsList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Card(
                    child: Padding(
                      padding: EdgeInsets.all(8),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            // width: MediaQuery.of(context).size.width * .75,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text('pharmacyId', style: labelTextStyle()),
                                    Text('bookingId',
                                        style: labelTextStyle()),
                                    Text('biddingAmount',
                                        style: labelTextStyle()),
                                  ],
                                ),
                                SizedBox(width: 5),
                                Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(':', style: labelTextStyle()),
                                    Text(':', style: labelTextStyle()),
                                    Text(':', style: labelTextStyle()),
                                  ],
                                ),
                                SizedBox(width: 5),
                                Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                        accountsList[index]
                                            .pharmacyId
                                            .toUpperCase(),
                                        style: valuesTextStyle()),
                                    Text(
                                        accountsList[index]
                                            .bookingId
                                            .toUpperCase(),
                                        style: valuesTextStyle()),
                                    Text(
                                        accountsList[index]
                                            .biddingAmount
                                            .toUpperCase()+' Ltrs',
                                        style: valuesTextStyle()),
                                  ],
                                ),
                              ],
                            ),
                          ),
                          Visibility(
                            visible: accountsList[index].orderStatus=='delivered' ,
                            child: Expanded(
                              child: TextButton(
                                onPressed: () {
                                  //modelBottomSheet(accountsList[index]);
                                },
                                child: const Text(
                                  'More Details',
                                  style: TextStyle(
                                    color: primaryColor,
                                    fontSize: 15,
                                    decoration: TextDecoration.underline,
                                  ),
                                ),
                              ),
                            ),)
                        ],
                      ),
                    ),
                  );
                })),
      ]);
    } else {
      return Center(
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
            child: isSereverIssue
                ? Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image(
                  image: AssetImage('images/updatepin.png.png'),
                  //  height: MediaQuery.of(context).size.height * .10,
                ),
                SizedBox(
                  height: 20,
                ),
                Text(
                  'There is an issue at server please try after some time',
                  style: serverIssueTextStyle(),
                ),
              ],
            )
                : Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image(
                  image: AssetImage('images/no_data.png'),
                  //  height: MediaQuery.of(context).size.height * .10,
                ),
                SizedBox(
                  height: 20,
                ),
                Text(
                  'No Data',
                  style: serverIssueTextStyle(),
                ),
              ],
            ),
          ));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppSettings.appBar('Accounts'),
      body: isLoading
          ? Center(
              child: CircularProgressIndicator(
                color: primaryColor,
                strokeWidth: 5.0,
              ),
            )
          : _accounsList(),
    );
  }
}
