import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:gen_service/Notifiers/ContactUsProvider.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import '../Utility/AppColors.dart';

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

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

  @override
  State<ContactUsScreen> createState() => _ContactUsScreenState();
}

class _ContactUsScreenState extends State<ContactUsScreen> {
  bool _stretch = true;

  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      final getInTouchProvider =
      Provider.of<ContactUsProvider>(context, listen: false);
      getInTouchProvider.fetchContactUs(widget.accId, widget.sessionId);
    });
  }

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

    final isLoading = getInTouchProvider.isLoading;
    final error = getInTouchProvider.errorMessage;
    final data = getInTouchProvider.response?.getInTouchList;

    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 || data.isEmpty) {
      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));
        getInTouchProvider.fetchContactUs(widget.accId, widget.sessionId);
      },
      child: Scaffold(
        backgroundColor: const Color(0xFF4076FF),
        body: CustomScrollView(
          physics: const ClampingScrollPhysics(),
          slivers: <Widget>[
            SliverAppBar(
              leading: Container(),
              stretch: _stretch,
              backgroundColor: const Color(0xFF4076FF),
              onStretchTrigger: () async {
                final provider =
                Provider.of<ContactUsProvider>(context, listen: false);
                provider.fetchContactUs(widget.accId, widget.sessionId);
              },
              stretchTriggerOffset: 300.0,
              expandedHeight: 245.0,
              flexibleSpace: FlexibleSpaceBar(
                stretchModes: const [
                  StretchMode.zoomBackground,
                  StretchMode.blurBackground,
                ],
                background: Container(
                  width: double.infinity,
                  decoration:
                  const BoxDecoration(gradient: AppColors.backgroundGradient),
                  child: SafeArea(
                    bottom: false,
                    child: Padding(
                      padding: const EdgeInsets.only(
                          top: 20, bottom: 25, left: 20, right: 20),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: const [
                          SizedBox(height: 16),
                          SizedBox(height: 8),
                          Text(
                            "Map view!.....",
                            style: TextStyle(fontSize: 22, color: Colors.white),
                          ),
                          SizedBox(height: 12),
                          SizedBox(height: 2),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),

            //  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: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical:  10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const SizedBox(height: 20),

                        ///  Build dynamic branch list
                        for (var item in data)
                          Padding(
                            padding: const EdgeInsets.only(bottom: 8.0),
                            child: _buildItemRow(
                              branchName: item.branchName ?? "Unknown Branch",
                              address: item.address ?? "No address available",
                              phoneNo: item.telephoneNo ?? "",
                              lat: item.latitude ?? "",
                              long: item.longitude ?? "",
                            ),
                          ),



                        const SizedBox(height: 30),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///  Branch card widget
  Widget _buildItemRow({
    required String branchName,
    required String address,
    required String phoneNo,
    required String lat,
    required String long,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(22)),
      child: Row(
        children: [
          const SizedBox(width: 14),
          Expanded(
            flex: 6,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  branchName,
                  style: const TextStyle(
                    color: AppColors.normalText,
                    fontWeight: FontWeight.w600,
                    fontSize: 14,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  address,
                  maxLines: 4,
                  style: const TextStyle(
                    color: AppColors.subtitleText,
                    fontWeight: FontWeight.w400,
                    fontSize: 14,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(width: 8),
          Row(
            children: [
              InkResponse(
                onTap: () {
                  //  map  lat & long
                },
                child: Container(
                  padding: const EdgeInsets.all(1),
                  decoration: BoxDecoration(
                      color: Colors.transparent,
                      borderRadius: BorderRadius.circular(30)),
                  child: SvgPicture.asset(
                    "assets/svg/route_ic.svg",
                    height: 42,
                    fit: BoxFit.contain,
                  ),
                ),
              ),
              const SizedBox(width: 6),
              InkResponse(
                onTap: () async {
                  final phone = phoneNo.trim();

                  if (phone.isEmpty) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        backgroundColor: Colors.redAccent,
                        content: const Text(
                          "Phone number not available",
                          style: TextStyle(color: Colors.white),
                        ),
                        duration: Duration(seconds: 2),
                        behavior: SnackBarBehavior.floating,
                      ),
                    );
                    return;
                  }

                  final Uri phoneUri = Uri(scheme: 'tel', path: phone);

                  try {
                    if (await canLaunchUrl(phoneUri)) {
                      await launchUrl(phoneUri);
                    } else {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          backgroundColor: Colors.redAccent,
                          content: const Text(
                            "Unable to start the call",
                            style: TextStyle(color: Colors.white),
                          ),
                          duration: Duration(seconds: 2),
                          behavior: SnackBarBehavior.floating,
                        ),
                      );
                    }
                  } catch (e) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        backgroundColor: Colors.redAccent,
                        content: Text(
                          "Error while trying to call: $e",
                          style: const TextStyle(color: Colors.white),
                        ),
                        duration: const Duration(seconds: 2),
                        behavior: SnackBarBehavior.floating,
                      ),
                    );
                  }
                },
                child: Container(
                  padding: const EdgeInsets.all(14),
                  decoration: BoxDecoration(
                    color: const Color(0xFF4CAF50),
                    borderRadius: BorderRadius.circular(30),
                  ),
                  child: SvgPicture.asset(
                    "assets/svg/phone_ic.svg",
                    height: 16,
                    color: Colors.white,
                    fit: BoxFit.contain,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
