import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:gen_service/Screens/ProfileScreen.dart';
import 'package:gen_service/Screens/TransactionListScreen.dart';
import 'package:provider/provider.dart';

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

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

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  bool _stretch = true;

  @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;

    if (isLoading) {
      return const Scaffold(
        backgroundColor: AppColors.backgroundRegular,
        body: Center(
          child: CircularProgressIndicator(color: AppColors.buttonColor,),
        ),
      );
    }

    if (error != null) {
      return Scaffold(
        backgroundColor: AppColors.backgroundRegular,
        body: Center(
          child: Text(
            error,
            style: const TextStyle(color: Colors.red, fontSize: 16),
          ),
        ),
      );
    }

    if (data == null) {
      return const Scaffold(
        backgroundColor: AppColors.backgroundRegular,
        body: Center(
          child: Text("No data found."),
        ),
      );
    }

    return RefreshIndicator.adaptive(
      color: AppColors.amountText,
      onRefresh: () async {
        await Future.delayed(const Duration(milliseconds: 600));
        Provider.of<DashboardProvider>(context, listen: false);
        dashboardProvider.fetchDashboard(widget.accId, widget.sessionId);
      },
      child: Scaffold(
        backgroundColor: Color(0xFF4076FF),
        body: CustomScrollView(
          physics:  ClampingScrollPhysics(),
          slivers: <Widget>[
            SliverAppBar(
              leading: Container(),
              stretch: _stretch,
              backgroundColor: Color(0xFF4076FF),
              onStretchTrigger: () async {
                // Refresh data when pulled down
                final dashboardProvider =
                Provider.of<DashboardProvider>(context, listen: false);
                dashboardProvider.fetchDashboard(widget.accId, widget.sessionId);
              },
              stretchTriggerOffset: 300.0,
              expandedHeight: 270.0,
              flexibleSpace: LayoutBuilder(
                builder: (context, constraints) {
                  final top = constraints.biggest.height;
                  return FlexibleSpaceBar(
                    stretchModes: const [
                      StretchMode.zoomBackground,
                      StretchMode.blurBackground,
                    ],
                    background: GestureDetector(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => ProfileScreen(
                              accId: widget.accId,
                              sessionId: widget.sessionId,
                            ),
                          ),
                        );
                      },
                      child: Container(
                        width: double.infinity,
                        decoration: const BoxDecoration(gradient: AppColors.backgroundGradient),
                        child: SafeArea(
                          bottom: false,
                          child: Padding(
                            padding: const EdgeInsets.only(top: 60, bottom: 60, left: 20, right: 20),
                            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: (data.userProfile?.isNotEmpty == true)
                                      ? Image.network(
                                    data.userProfile.toString(),
                                    fit: BoxFit.cover,
                                    errorBuilder: (context, error, stackTrace) =>
                                    const Icon(Icons.person,
                                        color: Color(0xFF2d2d2d), size: 40),
                                  )
                                      : CircleAvatar(
                                    radius: 40,
                                    backgroundColor: const Color(0xFFE0F4FF),
                                    child: SvgPicture.asset(
                                      height: 40,
                                      "assets/svg/person_ic.svg",
                                      fit: BoxFit.contain,
                                    ),
                                  ),
                                ),
                                const SizedBox(height: 16),
                                Flexible(
                                  child: Text(
                                    data.userName.toString(),
                                    style: const TextStyle(
                                      color: Colors.white,
                                      fontSize: 20,
                                      fontWeight: FontWeight.w600,
                                    ),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                const SizedBox(height: 8),
                                Text(
                                  '+91 ${data.mobNum}',
                                  style: TextStyle(
                                    color: Colors.white.withOpacity(0.9),
                                    fontSize: 14,
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                )
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),

            // Body content
            SliverToBoxAdapter(
              child: Container(
                padding: const EdgeInsets.only(top: 1, bottom: 0),
                color: Colors.transparent,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 0),
                  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),

                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 14),
                        child: Container(
                          padding: const EdgeInsets.all(20),
                          decoration: BoxDecoration(
                            color: const 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: 32, width: 32),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(height: 20),

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

  // ORDERS SECTION
  Widget _buildOrdersSection(dashboardData) {
    final orders = dashboardData.orders ?? [];
    if (orders.isEmpty) {
      return const Padding(
        padding: EdgeInsets.symmetric(vertical: 20, horizontal: 14),
        child: Center(
          child: Text("No Orders Found"),
        ),
      );
    }

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 14),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 16),
          ...orders.map<Widget>((order) {
            return Column(
              children: [
                _buildOrderItem(
                  assetId: "#${order.hashId ?? ''} | Engine : ${order.engine ?? ''}",
                  description: order.prodName ?? '',
                  amc: (order.amc?.toString() ?? ''),
                  warranty: (order.warranty?.toString() ?? ''),
                  pImage: 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(),
          // See All Button

        ],
      ),
    );
  }

  Widget _buildOrderItem({
    required String assetId,
    required String description,
    required String amc,
    required String warranty,
    required String pImage,
    String? date,
    String? serviceText,
  }) {
    return Container(
      padding: 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),

                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 14),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          // Status Badge with checkmark for AMC Protected
                          if (amc == "1" || amc == "2")
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                              decoration: BoxDecoration(
                                gradient: amc == "1"
                                    ? AppColors.greenStripGradient
                                    : AppColors.fadeGradient,
                                borderRadius: BorderRadius.circular(12),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Row(
                                    children: [
                                      SvgPicture.asset(
                                        "assets/svg/tick_ic.svg",
                                        height: 14,
                                        color: amc == "1"
                                            ? AppColors.greenICBg
                                            : AppColors.subtitleText,
                                      ),
                                      const SizedBox(width: 4),
                                      Text(
                                        "AMC ",
                                        style: TextStyle(
                                          fontSize: 11,
                                          fontFamily: "PoppinsBold",
                                          fontStyle: FontStyle.italic,
                                          fontWeight: FontWeight.w700,
                                          color: amc == "1"
                                              ? AppColors.greenICBg
                                              : AppColors.subtitleText,
                                        ),
                                      ),
                                      Text(
                                        "Protected",
                                        style: TextStyle(
                                          fontSize: 11,
                                          fontFamily: "PoppinsBold",
                                          fontStyle: FontStyle.italic,
                                          fontWeight: FontWeight.w700,
                                          color: amc == "1"
                                              ? AppColors.normalText
                                              : AppColors.subtitleText,
                                        ),
                                      ),
                                      SizedBox(width: 4,),
                                      if (amc == "2")
                                        const Icon(Icons.info_outline, color: Colors.red, size: 12,)
                                    ],
                                  ),
                                ],
                              ),
                            ),


                          // for warranty
                          if (warranty == "1" || warranty == "2")
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                              decoration: BoxDecoration(
                                gradient: warranty == "1"
                                    ? AppColors.yellowStripGradient
                                    : AppColors.fadeGradient,
                                borderRadius: BorderRadius.circular(12),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Row(
                                    children: [
                                      SvgPicture.asset(
                                        "assets/svg/tick2_ic.svg",
                                        height: 14,
                                        color: warranty == "1"
                                            ? AppColors.warning
                                            : AppColors.subtitleText,
                                      ),
                                      const SizedBox(width: 6),
                                      Text(
                                        "Warranty",
                                        style: TextStyle(
                                          fontSize: 11,
                                          fontFamily: "PoppinsBold",
                                          fontStyle: FontStyle.italic,
                                          fontWeight: FontWeight.w700,
                                          color: warranty == "1"
                                              ? AppColors.normalText
                                              : AppColors.subtitleText,
                                        ),
                                      ),
                                      SizedBox(width: 6,),
                                      if (warranty == "2")
                                        const Icon(Icons.info_outline, color: Colors.red, size: 12,)
                                    ],
                                  ),
                                ],
                              ),
                            ),
                        ],
                      ),
                    )

                  ],
                ),
              ),
              const SizedBox(width: 12),
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: const Color(0xffF2F2F2),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Image.network(
                  pImage.isNotEmpty ? pImage : "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: const 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,
                  ),
                  const 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 Padding(
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                'Transactions',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  color: Colors.black87,
                ),
              ),
              InkResponse(
                onTap: () {
                  Navigator.push(
                      context, MaterialPageRoute(builder: (context) => TransactionListScreen(accId: widget.accId, sessionId: widget.sessionId))
                  );
                },
                child: const Text(
                  'See All',
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                    color: AppColors.amountText,
                  ),
                ),
              ),
            ],
          ),
          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: const Color(0xAAFFFFFF),
                        fontSize: 12,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    const SizedBox(height: 10),
                    InkResponse(
                      onTap: () {
                        // Add pay now logic
                      },
                      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 Padding(
        padding: EdgeInsets.symmetric(vertical: 20),
        child: Center(
          child: Text(
            "No Complaints Found",
            style: TextStyle(fontSize: 14, color: Colors.grey),
          ),
        ),
      );
    }

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 14),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                "Complaints",
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  color: Colors.black87,
                ),
              ),
              Text(
                'See All',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: AppColors.amountText,
                ),
              ),
            ],
          ),
          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(),
        ],
      ),
    );
  }

}