
import 'package:cheminova/utils/show_snackbar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';

import '../../controller/kyc_controller.dart';
import '../../models/kyc_model.dart';
import 'kyc_verify_screen.dart';

class KycRetailerDetailScreen extends StatefulWidget {
  KycModel? kycModel;
  KycRetailerDetailScreen({super.key,this.kycModel});

  @override
  State<KycRetailerDetailScreen> createState() =>
      _KycRetailerDetailScreenState();
}

class _KycRetailerDetailScreenState
    extends State<KycRetailerDetailScreen> {

  final KycController _kycController = Get.put(KycController());
  final commentController = TextEditingController();
  String? currentStatus ;
  String selectedStatus = "All";

  void _approveKyc() {
    if (widget.kycModel!.status == "approved") {
      showSnackbar("The KYC has already been approved.");
    } else {
      // Show confirmation dialog
      Get.dialog(
        AlertDialog(
          title: Text("Approval Confirmation"),
          content: Text("Are you sure you want to approve this KYC?"),
          actions: [
            TextButton(
              onPressed: () {
                // Close the dialog without approving
                Get.back();
              },
              child: Text("Cancel"),
            ),
            TextButton(
              onPressed: () {
                // If "Approve" is pressed, approve the KYC
                _kycController.approveKyc(widget.kycModel!.id.toString());

                // Update the KYC status and show success message
                widget.kycModel!.status = "approved";

                showSnackbar("KYC approved successfully");

                // Delay closing the dialog to ensure the user sees the success message
                Future.delayed(Duration(seconds: 1), () {
                  Get.back(); // Close the dialog after a delay
                });

                setState(() {}); // Refresh the UI
              },
              child: Text("Approve"),
            ),
          ],
        ),
      );
    }
  }

  void _rejectKyc() {
    if (widget.kycModel!.status == "reject") {
      showSnackbar("The KYC has already been rejected");
      // Get.snackbar(
      //   "Error",
      //   "The KYC has already been rejected.",
      //   snackPosition: SnackPosition.BOTTOM,
      //   backgroundColor: Colors.red,
      //   colorText: Colors.white,
      // );
    } else {
      // Show dialog to enter a comment
      Get.dialog(
        AlertDialog(
          title: const Text("Reject KYC"),
          content: TextField(
            controller: commentController,
            decoration: const InputDecoration(hintText: "Enter rejection comment"),
          ),
          actions: [
            TextButton(
              onPressed: () {
                Get.back(); // Close dialog without action
              },
              child: const Text("Cancel"),
            ),
            TextButton(
              onPressed: () {
                String comment = commentController.text;
                if (comment.isNotEmpty) {
                  // Update the status in the model before calling the controller method
                  widget.kycModel!.status = "reject";

                  // Create a new Notes object (assuming Notes has a field for comments)
                  Notes rejectionNote = Notes(message: comment);

                  // Append the new Notes object to the notes list
                  widget.kycModel!.notes ??= []; // Initialize if null
                  widget.kycModel!.notes!.add(rejectionNote);

                  // Call the controller method with the updated notes
                  _kycController.rejectKyc(widget.kycModel!.id.toString(), widget.kycModel!.notes![0].message,"Principal Distributer");


        showSnackbar("KYC rejected successfully");

                  // Delay closing the dialog to ensure the user sees the success message
                  Future.delayed(Duration(seconds: 1), () {
                    Get.back(); // Close the dialog after a delay
                  });
                  setState(() {});
                  // Pass the updated model back to the previous screen
                 // Close the dialog
              // Pass the result back
                } else {
                  showSnackbar("Comment is required");

                }
              },
              child: const Text("Reject"),
            ),
          ],
        ),
      );
    }
  }












  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: GestureDetector(
          onTap: () {},
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: SvgPicture.asset(
              'assets/svg/menu.svg',
            ),
          ),
        ),
        actions: [
          GestureDetector(
            onTap: () => Get.back(),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: SvgPicture.asset(
                'assets/svg/back_arrow.svg',
              ),
            ),
          ),
        ],
        title: const Text(
          "Retail Distributer Detail",
        ),
      ),
      body: Stack(
        fit: StackFit.expand,
        children: [
          Image.asset(
            'assets/images/image_1.png',
            fit: BoxFit.cover,
          ),
          SafeArea(
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  SizedBox(
                    height: Get.height * 0.02,
                  ),
                  SizedBox(
                    height: Get.height * 0.85,
                    child: Card(
                      margin: const EdgeInsets.symmetric(horizontal: 18),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(19),
                        side: const BorderSide(color: Color(0xFFFDFDFD)),
                      ),
                      color: const Color(0xFFB4D1E5).withOpacity(0.9),
                      child: SingleChildScrollView(
                        child: Padding(
                          padding: const EdgeInsets.all(12.0),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              _buildCard(
                                title: "Retailer Information",
                                rows: [
                                  _buildInfoRow("Trade Name:", widget.kycModel!.tradeName),
                                  _buildInfoRow("Name:",  widget.kycModel!.name),
                                  _buildInfoRow("Address:",  widget.kycModel!.address),
                                  _buildInfoRow("Town/City:",  widget.kycModel!.city),
                                ],
                                width: Get.width,
                                height: Get.height,
                              ),
                              SizedBox(height: Get.height * 0.01),
                              _buildCard(
                                title: "Details",
                                rows: [
                                  _buildInfoRow("District:",  widget.kycModel!.district),
                                  _buildInfoRow("State:",  widget.kycModel!.state),
                                  _buildInfoRow("Pincode:",  widget.kycModel!.pincode),
                                  _buildInfoRow("Mobile Number:",  widget.kycModel!.mobileNumber),
                                  _buildInfoRow("Mapped Principal Distributor:",  widget.kycModel!.principalDistributer?.name),
                                ],
                                width: Get.width,
                                height: Get.height*0.5,
                              ),

                              SizedBox(height: Get.height * 0.01),
                              Card(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    _buildTitle(),
                                    _buildDocumentRow("Aadhaar number:", widget.kycModel!.aadharNumber, widget.kycModel!.aadharImg!.url),
                                    SizedBox(height: 10),
                                    _buildDocumentRow("Pan number:", widget.kycModel!.panNumber, widget.kycModel!.panImg!.url),
                                    SizedBox(height: 10),
                                    _buildDocumentRow("GST Number:", widget.kycModel!.gstNumber, widget.kycModel!.gstImg!.url),
                                    SizedBox(height: 10),
                                    _buildDocumentRow("Pesticide License:", "", widget.kycModel!.pesticideLicenseImg!.url),
                                    SizedBox(height: 10),
                                    _buildDocumentRow("Fertilizer License (optional):", "",widget.kycModel!.selfieEntranceImg!.url),
                                    SizedBox(height: 10),
                                    _buildDocumentRow("Selfie of Entrance Board::", "", widget.kycModel!.selfieEntranceImg!.url),
                                  ],
                                ),
                              ),
                              SizedBox(height: Get.height * 0.01),

                              SizedBox(
                                width: Get.width * 0.9,
                                child: Card(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      if (widget.kycModel!.status == "new")
                                        Padding(
                                        padding: const EdgeInsets.fromLTRB(16, 8, 8, 0),
                                        child: Text(
                                          "Verification Options",
                                          style: GoogleFonts.roboto(
                                            fontSize: 14,
                                            fontWeight: FontWeight.w700,
                                          ),
                                        ),
                                      ),
                                      // Conditionally render buttons based on KYC status
                                      if (widget.kycModel!.status == "new" ) ...[
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                          children: [
                                            SizedBox(
                                              width: Get.width * 0.4,
                                              child: Padding(
                                                padding: const EdgeInsets.all(8.0),
                                                child: ElevatedButton(
                                                  onPressed: _approveKyc,
                                                  style: ElevatedButton.styleFrom(
                                                    foregroundColor: Colors.white,
                                                    backgroundColor: const Color(0xFF004791),
                                                    shape: RoundedRectangleBorder(
                                                      borderRadius: BorderRadius.circular(10),
                                                    ),
                                                  ),
                                                  child: Text(
                                                    "Approve",
                                                    style: GoogleFonts.roboto(
                                                      fontSize: 14,
                                                      fontWeight: FontWeight.w400,
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ),
                                            SizedBox(
                                              width: Get.width * 0.4,
                                              child: Padding(
                                                padding: const EdgeInsets.all(8.0),
                                                child: ElevatedButton(
                                                  onPressed: _rejectKyc,
                                                  style: ElevatedButton.styleFrom(
                                                    foregroundColor: Colors.white,
                                                    backgroundColor: const Color(0xFF910000),
                                                    shape: RoundedRectangleBorder(
                                                      borderRadius: BorderRadius.circular(10),
                                                    ),
                                                  ),
                                                  child: Text(
                                                    "Reject",
                                                    style: GoogleFonts.roboto(
                                                      fontSize: 14,
                                                      fontWeight: FontWeight.w400,
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ],
                                  ),
                                ),
                              ),

                              SizedBox(height: Get.height * 0.01),
                              //SizedBox(height: Get.height * 0.01),
                              if (widget.kycModel!.status  == "reject") ...[
                                Card(
                                  child: SizedBox(
                                    width: Get.width * 0.9,
                                    height: Get.height * 0.2,
                                    child: Padding(
                                      padding: const EdgeInsets.all(12),
                                      child: Text(
                                        "Comment: ${widget.kycModel!.notes != null ? widget.kycModel!.notes!.map((note) => note.message).join(", ") : 'No comments'}",
                                        style: GoogleFonts.roboto(
                                          fontSize: Get.width * 0.04,
                                          fontWeight: FontWeight.w700,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),

                ],
              ),
            ),
          ),
        ],
      ),
    );
  }


  Widget _buildCard({required String title, required List<Widget> rows, required double width, required double height}) {
    return Card(
      child: Column(
        children: [
          _buildTitle1(title, width),
          ...rows,
        ],
      ),
    );
  }

  Widget _buildTitle1(String title, double width) {
    return SizedBox(
      width: width,
      child: Padding(
        padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
        child: Center(
          child: Text(
            title,
            style: GoogleFonts.roboto(
              fontSize: width * 0.04,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildInfoRow(String label, String? value) {
    return SizedBox(
      width: double.infinity,
      child: Padding(
        padding: const EdgeInsets.fromLTRB(5, 8, 8, 1),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              label,
              style: GoogleFonts.roboto(
                fontSize: 16, // Adjust as needed
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(width: 8), // Space between label and value
            Expanded(
              child: Text(value ?? 'N/A'), // Handle null case
            ),
          ],
        ),
      ),
    );
  }
}

  Widget _buildTitle() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 8, 8, 0),
      child: Center(
        child: Text(
          "KYC Documents",
          style: GoogleFonts.roboto(
            fontSize: Get.width * 0.04,// You can adjust this based on screen size
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }

  Widget _buildDocumentRow(String title, String? number, String? imageUrl) {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(16, 8, 8, 0),
          child: Row(
            children: [
              Text(title, style: TextStyle(fontWeight: FontWeight.bold)),
              SizedBox(width: 8), // Space between title and number
              Text(number ?? 'N/A'), // Handle null case
            ],
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: Image.network(
              imageUrl ?? 'No Image Available',
              fit: BoxFit.contain,
            ),
          ),
        ),
      ],
    );
  }


