import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';

import '../Notifiers/DashboardProvider.dart';
import '../Utility/AppColors.dart';

class ProfileScreen extends StatefulWidget {
  final String accId;
  final String sessionId;

  const ProfileScreen({
    Key? key,
    required this.accId,
    required this.sessionId,
  }) : super(key: key);

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      final dashboardProvider =
      Provider.of<DashboardProvider>(context, listen: false);
      dashboardProvider.fetchDashboard(widget.accId, widget.sessionId);
    });
  }

  @override
  Widget build(BuildContext context) {
    final dashboardProvider = Provider.of<DashboardProvider>(context);

    final isLoading = dashboardProvider.isLoading;
    final error = dashboardProvider.errorMessage;
    final data = dashboardProvider.dashboardData;

    return Scaffold(
      backgroundColor: AppColors.backgroundRegular,
      body: Stack(
        children: [
          if (isLoading)
            const Center(
              child: CircularProgressIndicator(),
            )
          else if (error != null)
            Center(
              child: Text(
                error,
                style: const TextStyle(color: Colors.red, fontSize: 16),
              ),
            )
          else if (data == null)
              const Center(
                child: Text("No data found."),
              )
            else
              Stack(
                children: [
                  /// 🔹 Profile Section
                  Positioned(
                    top: 0,
                    left: 0,
                    right: 0,
                    child: _buildProfileSection(
                      data.userProfile ?? "",
                      data.userName ?? "User",
                      data.mobNum ?? "",
                    ),
                  ),

                  /// 🔹 Scrollable Content
                  SafeArea(
                    child: SingleChildScrollView(
                      physics: const ClampingScrollPhysics(),
                      child: Column(
                        children: [
                          const SizedBox(height: 200),

                          /// Bottom Sheet style container
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 14),
                            width: double.infinity,
                            decoration: const BoxDecoration(
                              color: AppColors.backgroundRegular,
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(30),
                                topRight: Radius.circular(30),
                              ),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const SizedBox(height: 20),

                                // 🔹 Orders Section
                                _buildOrdersSection(data),

                                const SizedBox(height: 4),

                                // 🔹 Transactions Card
                                _buildTransactionsCard(data),

                                const SizedBox(height: 18),
                                const Divider(),

                                // 🔹 Complaints Section
                                _buildComplaintsSection(data),

                                const SizedBox(height: 20),

                                _buildFixIssuesCard(),
                                const SizedBox(height: 20),
                                // _buildGetInTouchCard(),
                                // const SizedBox(height: 30),
                              ],
                            ),
                          ),


                          Container(
                            width: double.infinity,
                            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
                            decoration: BoxDecoration(
                              color: AppColors.amountText,
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(24),
                                topRight: Radius.circular(24),
                              ),
                            ),
                            child: Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 16),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        'Get in touch With Us',
                                        style: TextStyle(
                                            fontSize: 14,
                                            fontWeight: FontWeight.w500,
                                            color: Colors.white),
                                      ),
                                      Text(
                                        'Please feel free to reach out to us anytime',
                                        style: TextStyle(
                                            fontSize: 12,
                                            fontWeight: FontWeight.w400,
                                            color: Color(0xAAFFFFFF)),
                                      ),
                                    ],
                                  ),
                                  Icon(Icons.arrow_circle_right_rounded,
                                      color: Color(0xFFFFFFFF), size: 30),
                                ],
                              ),
                            )
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
        ],
      ),
    );
  }


  // PROFILE SECTION
  // ===============================
  Widget _buildProfileSection(
      String userProfile, String userName, String userContact) {
    return Container(
      width: double.infinity,
      height: 275,
      padding: const EdgeInsets.only(top: 60, bottom: 60, left: 20, right: 20),
      decoration: const BoxDecoration(gradient: AppColors.backgroundGradient),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // Profile Image
          Container(
            height: 80,
            width: 80,
            decoration: const BoxDecoration(
              color: Color(0xFFE6F6FF),
              shape: BoxShape.circle,
            ),
            clipBehavior: Clip.antiAlias,
            child: (userProfile.isNotEmpty)
                ? Image.network(
              userProfile,
              fit: BoxFit.cover,
              errorBuilder: (context, error, stackTrace) =>
              const Icon(Icons.person,
                  color: Color(0xFF2d2d2d), size: 100),
            )
                : CircleAvatar(
              radius: 80,
              backgroundColor: const Color(0xFFE0F4FF),
              child: SvgPicture.asset(
                height: 80,
                "assets/svg/person_ic.svg",
                fit: BoxFit.contain,
              ),
            ),
          ),
          const SizedBox(height: 16),
          Text(
            userName,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 20,
              fontWeight: FontWeight.w600,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '+91 $userContact',
            style: TextStyle(
              color: Colors.white.withOpacity(0.9),
              fontSize: 14,
            ),
          )
        ],
      ),
    );
  }

  // ORDERS SECTION
  // ===============================
  Widget _buildOrdersSection(dashboardData) {
    final orders = dashboardData.orders ?? [];
    if (orders.isEmpty) {
      return const Center(
        child: Text("No Orders Found"),
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: orders.map<Widget>((order) {
        return Column(
          children: [
            _buildOrderItem(
              assetId: "#${order.hashId ?? ''} | Engine : ${order.engine ?? ''}",
              description: order.prodName ?? '',
              status: (order.amc?.isNotEmpty ?? false)
                  ? 'AMC Protected'
                  : (order.warranty?.isNotEmpty ?? false)
                  ? 'WARRANTY'
                  : 'Unknown',
              statusColor: (order.amc?.isNotEmpty ?? false)
                  ? Colors.green
                  : (order.warranty?.isNotEmpty ?? false)
                  ? Colors.orange
                  : Colors.grey,
              p_imagae: order.productImage ?? '',
              date: order.schedule?.isNotEmpty == true
                  ? order.schedule!.first
                  : null,
              serviceText: order.schedule?.isNotEmpty == true
                  ? 'Upcoming Service Scheduled'
                  : null,
            ),
            const SizedBox(height: 12),
          ],
        );
      }).toList(),
    );
  }


  Widget _buildOrderItem({
    required String assetId,
    required String description,
    required String status,
    required Color statusColor,
    required String p_imagae,
    String? date,
    String? serviceText,
  }) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      assetId,
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w400,
                        color: AppColors.amountText,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      description,
                      style: TextStyle(
                        fontSize: 14,
                        color: AppColors.normalText,
                        height: 1.4,
                      ),
                    ),

                    const SizedBox(height: 8),

                    // Status Badge with checkmark for AMC Protected
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(
                        color: statusColor.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(6),
                        border: Border.all(
                          color: statusColor.withOpacity(0.3),
                        ),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          if (status == 'AMC Protected')
                            const Icon(
                              Icons.check_circle,
                              color: Colors.green,
                              size: 12,
                            ),
                          if (status == 'AMC Protected') const SizedBox(width: 4),
                          Text(
                            status,
                            style: TextStyle(
                              fontSize: 10,
                              fontWeight: FontWeight.w600,
                              color: statusColor,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),

              const SizedBox(width: 12),

              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: const Color(0xffF2F2F2),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Image.network(
                  p_imagae ?? "https://erp.gengroup.in/assets/upload/inventory_add_genesis_product_pic/_1761047459_6425.png",
                  height: 50,
                  width: 50,
                  fit: BoxFit.contain,
                  errorBuilder: (context, error, stack) =>
                      Image.asset('assets/images/dashboard_gen.png',
                          height: 40,
                          width: 40),
                ),
              ),
            ],
          ),
          // Date and Service Text for first item
          if (date != null && serviceText != null) ...[
            const SizedBox(height: 12),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 14, vertical: 12),
              decoration: BoxDecoration(
                color: const Color(0xffF2F2F2),
                borderRadius: BorderRadius.circular(16),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  SvgPicture.asset(
                    height: 30,
                    "assets/svg/checked_ic.svg",
                    fit: BoxFit.contain,
                  ),
                  SizedBox(width: 10,),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        date,
                        style: TextStyle(
                          fontSize: 12,
                          color: AppColors.normalText,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      Text(
                        serviceText,
                        style: TextStyle(
                          fontSize: 12,
                          color: AppColors.subtitleText,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),

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


  // TRANSACTIONS CARD
  // ===============================
  Widget _buildTransactionsCard(dashboardData) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              'Transactions',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
                color: Colors.black87,
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(22),
          decoration: BoxDecoration(
            gradient: AppColors.balanceCardGradientP,
            borderRadius: BorderRadius.circular(16),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "₹",
                        style: TextStyle(

                          color: Colors.white,
                          fontSize: 20,
                          height: 2,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      Text(
                        dashboardData?.balanceAmount?.toString() ?? "0",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 34,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  Row(
                    children: [
                      const Icon(Icons.info_outline,
                          color: Colors.white, size: 16),
                      const SizedBox(width: 6),
                      Text(
                        dashboardData.balanceType ?? 'Pending Balance',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              Column(
                children: [
                  Text(
                    "*Make sure to pay before\n you incur any fines.",
                    maxLines: 2,
                    style: TextStyle(
                      color: Color(0xAAFFFFFF),
                      fontSize: 12,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  SizedBox(height: 10,),
                  InkResponse(
                    child: Container(
                      padding:
                      const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: const Text(
                        " Pay Now ",
                        style: TextStyle(
                          color: Colors.blue,
                          fontFamily: "Poppins",
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ],
    );
  }

  // COMPLAINTS SECTION
  // ===============================
  Widget _buildComplaintsSection(dashboardData) {
    final complaints = dashboardData.complaints ?? [];

    if (complaints.isEmpty) {
      return const Center(
        child: Text(
          "No Complaints Found",
          style: TextStyle(fontSize: 14, color: Colors.grey),
        ),
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 8),
        const Text(
          "Complaints",
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 8),

        ...complaints.map<Widget>((c) {
          return Container(
            margin: const EdgeInsets.only(bottom: 10),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.grey.shade200),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.03),
                  blurRadius: 6,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                /// 🔹 Top row — Complaint name and status
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Complaint info
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "#${c.hashId ?? ''} | ${c.complaintName ?? ''}",
                            style: const TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              color: AppColors.amountText,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            c.registredDate ?? '',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey.shade600,
                            ),
                          ),
                        ],
                      ),
                    ),

                    // Status badge
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 16, vertical: 8),
                      decoration: BoxDecoration(
                        color: (c.openStatus?.toLowerCase() == 'open')
                            ? AppColors.successBG
                            : AppColors.warningBg2,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Text(
                        c.openStatus ?? '',
                        style: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w600,
                          color: (c.openStatus?.toLowerCase() == 'open')
                              ? AppColors.success
                              : AppColors.warningText,
                        ),
                      ),
                    ),
                  ],
                ),

                const SizedBox(height: 12),
                const Divider(),

                /// 🔹 Product Info Row
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    // Product details
                    Text(
                      c.productName ?? "Unknown Product",
                      style: const TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                        color: AppColors.normalText,
                      ),
                    ),

                    // Product ID
                    Row(
                      children: [
                        Text(
                          "#${c.id ?? ''} | ",
                          style: const TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.w500,
                            color: AppColors.subtitleText,
                          ),
                        ),

                        if ((c.modelName ?? '').isNotEmpty)
                          Text(
                            "Engine: ${c.modelName}",
                            style: TextStyle(
                              fontSize: 12,
                              color: AppColors.subtitleText,
                            ),
                          ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          );
        }).toList(),
      ],
    );
  }



  // ===============================
  // The remaining helper cards (no changes)
  // ===============================
  Widget _buildFixIssuesCard() => // same as before
  Container(
    padding: const EdgeInsets.all(20),
    decoration: BoxDecoration(
      color: Color(0xFFD7F0FF),
      borderRadius: BorderRadius.circular(16),
      border: Border.all(width: 1.5, color: AppColors.buttonColor),
    ),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: const [
            Text('Facing Issues?',
                style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                    color: AppColors.amountText)),
            Text(
              'Raise a ticket to resolve your issues.',
              style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w400,
                  color: AppColors.subtitleText),
            ),
          ],
        ),
        SvgPicture.asset("assets/svg/requirements.svg",
            height: 22, width: 22),
      ],
    ),
  );

  Widget _buildGetInTouchCard() => // same as before
  Container(
    padding: const EdgeInsets.all(20),
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(16),
      border: Border.all(color: Colors.grey.shade200),
      boxShadow: [
        BoxShadow(
          color: Colors.black.withOpacity(0.05),
          blurRadius: 8,
          offset: const Offset(0, 2),
        ),
      ],
    ),
    child: const Row(
      children: [
        Icon(Icons.support_agent,
            color: Color(0xFF1487C9), size: 24),
        SizedBox(width: 16),
        Expanded(
          child: Text(
            'Get in touch With Us',
            style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: Colors.black87),
          ),
        ),
      ],
    ),
  );
}
