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

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

class QuotationListScreen extends StatefulWidget {
  final accId;
  final sessionId;
  final genId;

  const QuotationListScreen({
    super.key,
    required this.accId,
    required this.sessionId,
    required this.genId,
  });

  @override
  State<QuotationListScreen> createState() => _QuotationListScreenState();
}

class _QuotationListScreenState extends State<QuotationListScreen> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      final provider = Provider.of<Generatordetailsprovider>(
        context,
        listen: false,
      );
      provider.fetchQuotationList(widget.accId, widget.sessionId, widget.genId);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<Generatordetailsprovider>(
      builder: (context, provider, child) {
        final isLoading = provider.isLoading;
        final error = provider.errorMessage;
        final response = provider.quotationResponse;

        final data = response?.serviceQuotation ?? [];

        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: Padding(
                padding: const EdgeInsets.all(24.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // Error Icon
                    Container(
                      width: 120,
                      height: 120,
                      decoration: BoxDecoration(
                        color: Colors.red.withOpacity(0.1),
                        shape: BoxShape.circle,
                      ),
                      child: const Icon(
                        Icons.error_outline_rounded,
                        size: 60,
                        color: Colors.red,
                      ),
                    ),

                    const SizedBox(height: 24),

                    // Error Title
                    const Text(
                      "Oops! Something went wrong",
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.w600,
                        color: Colors.black87,
                        fontFamily: "Poppins",
                      ),
                    ),

                    const SizedBox(height: 12),

                    // Error Message
                    Text(
                      error,
                      textAlign: TextAlign.center,
                      style: const TextStyle(
                        fontSize: 14,
                        color: Colors.grey,
                        fontFamily: "Poppins",
                        height: 1.4,
                      ),
                    ),

                    const SizedBox(height: 32),

                    // Retry Button
                    ElevatedButton.icon(
                      onPressed: () async {
                        // Show loading state
                        setState(() {});

                        await Future.delayed(const Duration(milliseconds: 300));

                        // Retry fetching data
                        final provider = Provider.of<Generatordetailsprovider>(
                          context,
                          listen: false,
                        );
                        await provider.fetchQuotationList(
                          widget.accId,
                          widget.sessionId,
                          widget.genId,
                        );
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColors.buttonColor,
                        foregroundColor: Colors.white,
                        padding: const EdgeInsets.symmetric(
                          horizontal: 24,
                          vertical: 12,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(25),
                        ),
                        elevation: 2,
                      ),
                      icon: const Icon(Icons.refresh_rounded, size: 20),
                      label: const Text(
                        "Try Again",
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                          fontFamily: "Poppins",
                        ),
                      ),
                    ),

                    const SizedBox(height: 16),

                    // Alternative Action
                    TextButton(
                      onPressed: () {
                        // Go back or navigate to home
                        Navigator.maybePop(context);
                      },
                      child: const Text(
                        "Go Back",
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey,
                          fontFamily: "Poppins",
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        }
        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));
          },

          child: Scaffold(
            backgroundColor: AppColors.backgroundRegular,
            body: CustomScrollView(
              physics: const BouncingScrollPhysics(),
              slivers: [
                SliverAppBar(
                  stretch: true,
                  pinned: true,
                  expandedHeight: 75,
                  backgroundColor: AppColors.backgroundRegular,
                  elevation: 0,
                  // Remove shadow
                  automaticallyImplyLeading: false,
                  toolbarHeight: 0,
                  // Remove toolbar space
                  collapsedHeight: 0,
                  // Completely collapse to 0 height
                  flexibleSpace: FlexibleSpaceBar(
                    stretchModes: const [StretchMode.fadeTitle],
                    background: Container(
                      decoration: BoxDecoration(
                        gradient: AppColors.balanceBarGradientA,
                      ),
                      child: SafeArea(
                        child: Padding(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 20,
                          ),
                          child: SizedBox(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                InkResponse(
                                  onTap: () {
                                    HapticFeedback.selectionClick();

                                    Navigator.pop(context, true);
                                  },
                                  child: SvgPicture.asset(
                                    "assets/svg/appbar_back.svg",
                                    height: 25,
                                  ),
                                ),
                                SizedBox(width: 10),
                                Expanded(
                                  flex: 4,
                                  child: InkResponse(
                                    onTap: () {
                                      HapticFeedback.selectionClick();

                                      Navigator.pop(context, true);
                                    },
                                    child: Text(
                                      "Quotations List",
                                      overflow: TextOverflow.ellipsis,
                                      maxLines: 1,
                                      style: TextStyle(
                                        fontSize: 16,
                                        color: Colors.white,
                                        height: 1.1,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),

                SliverToBoxAdapter(
                  child: Container(
                    color: Color(0xFF4076FF),
                    child: Container(
                      decoration: const BoxDecoration(
                        color: AppColors.backgroundRegular,
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(30),
                          topRight: Radius.circular(30),
                        ),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(height: 4),

                          ListView.builder(
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                            itemCount: data!.length,
                            itemBuilder: (context, j) {
                              return InkResponse(
                                onTap: () {
                                  // _handleDownload(
                                  //   context,
                                  //   data.quoteFilepath!,
                                  //   contentDisposition,
                                  //   'application/octet-stream',
                                  //   '',
                                  // );
                                  String suggestedFilename = provider
                                      .getUniqueFilename('quotation', 'pdf');
                                  String contentDisposition =
                                      'attachment; filename="$suggestedFilename"';

                                  provider.handleDownload(
                                    context,
                                    data[j].fileLoc!,
                                    contentDisposition,
                                    'application/octet-stream',
                                    '',
                                  );
                                },
                                child: Container(
                                  padding: const EdgeInsets.symmetric(
                                    vertical: 10,
                                    horizontal: 10,
                                  ),
                                  margin: const EdgeInsets.symmetric(
                                    vertical: 5,
                                    horizontal: 10,
                                  ),
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(12),
                                  ),
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Expanded(
                                        flex: 4,
                                        child: Text(
                                          data[j].title ?? "-",
                                          maxLines: 2,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(fontSize: 14),
                                        ),
                                      ),
                                      Expanded(
                                        flex: 3,
                                        child: Text(
                                          data[j].date ?? "-",
                                          textAlign: TextAlign.right,
                                          style: TextStyle(fontSize: 14),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            },
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
