import 'dart:convert';
import 'dart:developer' show log;
import 'dart:math' show Random;

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:payg/activity/WebViewContainer.dart';
import 'package:payg/model/payment_success.dart';

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

  @override
  State<PayOrder> createState() => _PayOrderState();
}

class _PayOrderState extends State<PayOrder> {
  // --- Config (⚠️ move these server-side before release) ---
  static const String paymentURL = 'https://uatapiv2.payg.in/payment/api/order';
  static const String authenticationKey = '0ca4cd6e43204581ac6efeba64ea7d56';
  static const String authenticationToken = 'b2a1566d6dda47e69449ce6e79f6644a';
  static const String merchantKeyId = '7963';
  static const String mid = 'F7E600079463648';

  static const String redirectUrl = 'https://payg.in/';

  final _formKey = GlobalKey<FormState>();
  bool _isSubmitting = false;
  String? _errorMessage;
  bool _showAdvanced = false;

  static const _chars =
      'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
  final _rnd = Random();

  // Required fields
  final orderAmountController = TextEditingController();
  final orderFirstNameController = TextEditingController();
  final orderLastNameController = TextEditingController();
  final mobileNoController = TextEditingController();

  // Optional fields
  final emailController = TextEditingController();
  final customerNotesController = TextEditingController();
  final billingAddressController = TextEditingController();
  final billingCityController = TextEditingController();
  final billingStateController = TextEditingController();
  final billingCountryController = TextEditingController();
  final billingZipController = TextEditingController();
  final shippingFirstNameController = TextEditingController();
  final shippingLastNameController = TextEditingController();
  final shippingAddressController = TextEditingController();
  final shippingCityController = TextEditingController();
  final shippingStateController = TextEditingController();
  final shippingCountryController = TextEditingController();
  final shippingZipController = TextEditingController();
  final shippingMobileController = TextEditingController();

  @override
  void dispose() {
    for (final c in [
      orderAmountController,
      orderFirstNameController,
      orderLastNameController,
      mobileNoController,
      emailController,
      customerNotesController,
      billingAddressController,
      billingCityController,
      billingStateController,
      billingCountryController,
      billingZipController,
      shippingFirstNameController,
      shippingLastNameController,
      shippingAddressController,
      shippingCityController,
      shippingStateController,
      shippingCountryController,
      shippingZipController,
      shippingMobileController,
    ]) {
      c.dispose();
    }
    super.dispose();
  }

  String _getRandomString(int length) => String.fromCharCodes(
    Iterable.generate(
      length,
      (_) => _chars.codeUnitAt(_rnd.nextInt(_chars.length)),
    ),
  );

  Future<void> _createOrder() async {
    setState(() {
      _isSubmitting = true;
      _errorMessage = null;
    });

    try {
      final data = {
        //"Merchantkeyid": merchantKeyId,
        "MID": mid,
        "UniqueRequestId": _getRandomString(10),
        "OrderStatus": 'Initiating',
        "UserDefinedData": {"UserDefined1": ''},
        "RequestDateTime": DateTime.now().toIso8601String(),
        "RedirectUrl": redirectUrl,
        "TransactionData": {
          "AcceptedPaymentTypes": '',
          "PaymentType": '',
          "SurchargeType": '',
          "SurchargeValue": '',
          "RefTransactionId": '',
          "IndustrySpecificationCode": '',
          "PartialPaymentOption": '',
        },

        "OrderAmount": orderAmountController.text,
        "OrderType": 'MOBILE',
        "OrderAmountData": {
          "AmountTypeDesc": '',
          "Amount": orderAmountController.text,
        },
        "CustomerData": {
          'CustomerId': '',
          'CustomerNotes': customerNotesController.text,
          'FirstName': orderFirstNameController.text,
          'LastName': orderLastNameController.text,
          'MobileNo': mobileNoController.text,
          'Email': emailController.text,
          'EmailReceipt': 'true',
          'BillingAddress': billingAddressController.text,
          'BillingCity': billingCityController.text,
          'BillingState': billingStateController.text,
          'BillingCountry': billingCountryController.text,
          'BillingZipCode': billingZipController.text,
          'ShippingFirstName': shippingFirstNameController.text,
          'ShippingLastName': shippingLastNameController.text,
          'ShippingAddress': shippingAddressController.text,
          'ShippingCity': shippingCityController.text,
          'ShippingState': shippingStateController.text,
          'ShippingCountry': shippingCountryController.text,
          'ShippingZipCode': shippingZipController.text,
          'ShippingMobileNo': shippingMobileController.text,
        },
        "IntegrationData": {
          "UserName": '',
          "Source": 'MobileSDK',
          "IntegrationType": "11",
          "HashData": '',
          "PlatformId": '',
        },
      };

      final jsonString = json.encode(data);
      final credentials = '$authenticationKey:$authenticationToken:M:$mid';
      final encoded = utf8.fuse(base64).encode(credentials);
      log("jsonString ${jsonString}");

      final response = await http.post(
        Uri.parse('$paymentURL/create'),
        headers: {
          'Content-type': 'application/json',
          'Authorization': 'Basic $encoded',
        },
        body: jsonString,
      );

      final jsonResponse = jsonDecode(response.body);
      log("response ${response.body}");

      if (response.statusCode != 200 ||
          jsonResponse['PaymentProcessUrl'] == null) {
        throw Exception('Order creation failed. Please try again.');
      }

      PaymentSuccess paymentSuccess = paymentSuccessFromJson(
        response.body,
      ); // keep parsing for downstream use

      if (!mounted) return;
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) =>
              WebViewContainer(paymentSuccess.paymentProcessUrl!),
        ),
      );
    } catch (e) {
      setState(() => _errorMessage = 'Something went wrong. Please try again.');
    } finally {
      if (mounted) setState(() => _isSubmitting = false);
    }
  }

  void _submit() {
    final isValid = _formKey.currentState!.validate();
    if (!isValid) return;
    _formKey.currentState!.save();
    _createOrder();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F7FA),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(
            Icons.arrow_back_ios_new_rounded,
            color: Colors.black87,
            size: 20,
          ),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text(
          'Create Order',
          style: TextStyle(
            fontSize: 17,
            color: Colors.black87,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: false,
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(20),
          child: Form(
            key: _formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _SectionCard(
                  title: 'Order Details',
                  children: [
                    _StyledField(
                      controller: orderAmountController,
                      label: 'Order Amount',
                      hint: 'e.g. 500',
                      icon: Icons.currency_rupee_rounded,
                      keyboardType: TextInputType.number,
                      required: true,
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                _SectionCard(
                  title: 'Customer Details',
                  children: [
                    _StyledField(
                      controller: orderFirstNameController,
                      label: 'First Name',
                      icon: Icons.person_outline_rounded,
                      required: true,
                    ),
                    const SizedBox(height: 14),
                    _StyledField(
                      controller: orderLastNameController,
                      label: 'Last Name',
                      icon: Icons.person_outline_rounded,
                      required: true,
                    ),
                    const SizedBox(height: 14),
                    _StyledField(
                      controller: mobileNoController,
                      label: 'Mobile Number',
                      icon: Icons.phone_outlined,
                      keyboardType: TextInputType.phone,
                      required: true,
                    ),
                    const SizedBox(height: 14),
                    _StyledField(
                      controller: emailController,
                      label: 'Email',
                      icon: Icons.email_outlined,
                      keyboardType: TextInputType.emailAddress,
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                _ExpandableSection(
                  title: 'Additional Details',
                  subtitle: 'Billing, shipping & optional info',
                  expanded: _showAdvanced,
                  onToggle: () =>
                      setState(() => _showAdvanced = !_showAdvanced),
                  children: [
                    _StyledField(
                      controller: customerNotesController,
                      label: 'Customer Notes',
                      icon: Icons.notes_rounded,
                    ),
                    const SizedBox(height: 14),
                    _StyledField(
                      controller: billingAddressController,
                      label: 'Billing Address',
                      icon: Icons.home_outlined,
                    ),
                    const SizedBox(height: 14),
                    Row(
                      children: [
                        Expanded(
                          child: _StyledField(
                            controller: billingCityController,
                            label: 'City',
                            icon: Icons.location_city_outlined,
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: _StyledField(
                            controller: billingStateController,
                            label: 'State',
                            icon: Icons.map_outlined,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 14),
                    Row(
                      children: [
                        Expanded(
                          child: _StyledField(
                            controller: billingCountryController,
                            label: 'Country',
                            icon: Icons.public_outlined,
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: _StyledField(
                            controller: billingZipController,
                            label: 'Zip Code',
                            icon: Icons.pin_drop_outlined,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 20),
                    Text(
                      'Shipping Info',
                      style: TextStyle(
                        fontWeight: FontWeight.w600,
                        color: Colors.grey.shade700,
                      ),
                    ),
                    const SizedBox(height: 12),
                    Row(
                      children: [
                        Expanded(
                          child: _StyledField(
                            controller: shippingFirstNameController,
                            label: 'First Name',
                            icon: Icons.person_outline_rounded,
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: _StyledField(
                            controller: shippingLastNameController,
                            label: 'Last Name',
                            icon: Icons.person_outline_rounded,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 14),
                    _StyledField(
                      controller: shippingAddressController,
                      label: 'Shipping Address',
                      icon: Icons.local_shipping_outlined,
                    ),
                    const SizedBox(height: 14),
                    Row(
                      children: [
                        Expanded(
                          child: _StyledField(
                            controller: shippingCityController,
                            label: 'City',
                            icon: Icons.location_city_outlined,
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: _StyledField(
                            controller: shippingStateController,
                            label: 'State',
                            icon: Icons.map_outlined,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 14),
                    Row(
                      children: [
                        Expanded(
                          child: _StyledField(
                            controller: shippingCountryController,
                            label: 'Country',
                            icon: Icons.public_outlined,
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: _StyledField(
                            controller: shippingZipController,
                            label: 'Zip Code',
                            icon: Icons.pin_drop_outlined,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 14),
                    _StyledField(
                      controller: shippingMobileController,
                      label: 'Shipping Mobile No.',
                      icon: Icons.phone_outlined,
                      keyboardType: TextInputType.phone,
                    ),
                  ],
                ),
                const SizedBox(height: 24),
                if (_errorMessage != null)
                  Container(
                    margin: const EdgeInsets.only(bottom: 16),
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.red.shade50,
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(color: Colors.red.shade100),
                    ),
                    child: Row(
                      children: [
                        Icon(
                          Icons.error_outline_rounded,
                          color: Colors.red.shade400,
                          size: 20,
                        ),
                        const SizedBox(width: 8),
                        Expanded(
                          child: Text(
                            _errorMessage!,
                            style: TextStyle(
                              color: Colors.red.shade700,
                              fontSize: 13,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                SizedBox(
                  width: double.infinity,
                  height: 54,
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0xFF1F6FEB),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(14),
                      ),
                      elevation: 0,
                    ),
                    onPressed: _isSubmitting ? null : _submit,
                    child: _isSubmitting
                        ? const SizedBox(
                            width: 22,
                            height: 22,
                            child: CircularProgressIndicator(
                              strokeWidth: 2.4,
                              color: Colors.white,
                            ),
                          )
                        : const Text(
                            'Proceed to Pay',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: Colors.white,
                            ),
                          ),
                  ),
                ),
                const SizedBox(height: 24),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

// ---------------- Reusable pieces ----------------

class _SectionCard extends StatelessWidget {
  final String title;
  final List<Widget> children;

  const _SectionCard({required this.title, required this.children});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(18),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(18),
        border: Border.all(color: Colors.grey.shade200),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: const TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.w700,
              color: Colors.black87,
            ),
          ),
          const SizedBox(height: 16),
          ...children,
        ],
      ),
    );
  }
}

class _ExpandableSection extends StatelessWidget {
  final String title;
  final String subtitle;
  final bool expanded;
  final VoidCallback onToggle;
  final List<Widget> children;

  const _ExpandableSection({
    required this.title,
    required this.subtitle,
    required this.expanded,
    required this.onToggle,
    required this.children,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(18),
        border: Border.all(color: Colors.grey.shade200),
      ),
      child: Column(
        children: [
          InkWell(
            borderRadius: BorderRadius.circular(18),
            onTap: onToggle,
            child: Padding(
              padding: const EdgeInsets.all(18),
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          title,
                          style: const TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.w700,
                            color: Colors.black87,
                          ),
                        ),
                        const SizedBox(height: 2),
                        Text(
                          subtitle,
                          style: TextStyle(
                            fontSize: 12.5,
                            color: Colors.grey.shade600,
                          ),
                        ),
                      ],
                    ),
                  ),
                  AnimatedRotation(
                    turns: expanded ? 0.5 : 0,
                    duration: const Duration(milliseconds: 200),
                    child: Icon(
                      Icons.keyboard_arrow_down_rounded,
                      color: Colors.grey.shade600,
                    ),
                  ),
                ],
              ),
            ),
          ),
          AnimatedCrossFade(
            firstChild: const SizedBox(width: double.infinity),
            secondChild: Padding(
              padding: const EdgeInsets.fromLTRB(18, 0, 18, 18),
              child: Column(children: children),
            ),
            crossFadeState: expanded
                ? CrossFadeState.showSecond
                : CrossFadeState.showFirst,
            duration: const Duration(milliseconds: 200),
          ),
        ],
      ),
    );
  }
}

class _StyledField extends StatelessWidget {
  final TextEditingController controller;
  final String label;
  final String? hint;
  final IconData icon;
  final TextInputType keyboardType;
  final bool required;

  const _StyledField({
    required this.controller,
    required this.label,
    required this.icon,
    this.hint,
    this.keyboardType = TextInputType.text,
    this.required = false,
  });

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      controller: controller,
      keyboardType: keyboardType,
      validator: required
          ? (value) =>
                (value == null || value.isEmpty) ? 'Please enter $label' : null
          : null,
      decoration: InputDecoration(
        labelText: required ? '$label *' : label,
        hintText: hint,
        prefixIcon: Icon(icon, size: 20, color: Colors.grey.shade500),
        filled: true,
        fillColor: const Color(0xFFF5F7FA),
        contentPadding: const EdgeInsets.symmetric(
          vertical: 14,
          horizontal: 12,
        ),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide.none,
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: const BorderSide(color: Color(0xFF1F6FEB), width: 1.5),
        ),
        errorBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(color: Colors.red.shade300),
        ),
      ),
    );
  }
}
