import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_color.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_font_size.dart';
import 'package:niogu_ecommerce_v1/core/router/app_route.dart';
import 'package:niogu_ecommerce_v1/core/widgets/custom_empty_screen.dart';
import 'package:niogu_ecommerce_v1/features/account/domain/entities/account.dart';
import 'package:niogu_ecommerce_v1/features/account/presentation/providers/account_provider.dart';
import 'package:sizer/sizer.dart';

class ShippingAddressScreen extends ConsumerWidget {
  const ShippingAddressScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final customerAddressState = ref.watch(
          customerAddressControllerProvider,
        );

        final selectedAddress = ref.watch(selectedAddressProvider);

        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: const Color(0xFFF8F9FA),
            appBar: AppBar(
              backgroundColor: Colors.white,
              elevation: 0.5,
              leading: IconButton(
                icon: Icon(
                  Icons.arrow_back,
                  color: AppColor.primaryColor,
                  size: 7.w,
                ),
                onPressed: () => context.pop(),
              ),
              title: Text(
                "Pilih Alamat Pengiriman",
                style: TextStyle(
                  color: Colors.black,
                  fontSize: AppFontSize.medium.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            body: Column(
              children: [
                Expanded(
                  child: customerAddressState.when(
                    data: (addresses) {
                      if (addresses.isEmpty) {
                        return CustomEmptyScreen(
                          icon: Icons.search_off_outlined,
                          title: "Belum Ada Alamat",
                          subtitle: "Tambahkan alamat pertamamu",
                          height: 40.h,
                        );
                      }
                      return ListView.builder(
                        padding: EdgeInsets.symmetric(vertical: 2.h),
                        itemCount: addresses.length,
                        itemBuilder: (context, index) {
                          final address = addresses[index];
                          final isSelected =
                              selectedAddress?.id == address.uuid;

                          return _buildSelectableAddressItem(
                            context,
                            ref,
                            address,
                            isSelected,
                          );
                        },
                      );
                    },
                    error: (error, stackTrace) => CustomEmptyScreen(
                      icon: Icons.cloud_off_outlined,
                      title: "Terjadi Kesalahan Koneksi",
                      height: 40.h,
                    ),
                    loading: () => const Center(
                      child: CircularProgressIndicator(
                        color: AppColor.primaryColor,
                        backgroundColor: Colors.white,
                      ),
                    ),
                  ),
                ),

                if (!customerAddressState.isLoading) ...[
                  if (customerAddressState.hasValue &&
                      customerAddressState.value!.isNotEmpty)
                    _buildConfirmButton(context, ref, selectedAddress)
                  else
                    _buildAddAddressButton(context),
                ],
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildSelectableAddressItem(
    BuildContext context,
    WidgetRef ref,
    CustomerAddress address,
    bool isSelected,
  ) {
    final selectedAddress = SelectedAddress(
      id: address.uuid,
      label: address.label,
      fullAddress: address.fullAddress,
      latitude: address.latitude,
      longitude: address.longitude,
    );
    return GestureDetector(
      onTap: () =>
          ref.read(selectedAddressProvider.notifier).state = selectedAddress,
      child: Container(
        margin: EdgeInsets.fromLTRB(4.w, 0, 4.w, 1.5.h),
        padding: EdgeInsets.all(4.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(2.5.w),
          border: Border.all(color: Colors.grey.shade200, width: 1),
        ),
        child: Row(
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    address.label,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: AppFontSize.small.sp,
                    ),
                  ),
                  SizedBox(height: 1.h),
                  Text(
                    address.fullAddress,
                    style: TextStyle(
                      fontSize: (AppFontSize.small - 1).sp,
                      color: Colors.grey.shade600,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
            if (isSelected)
              Icon(Icons.check_circle, color: AppColor.primaryColor, size: 7.w)
            else
              Icon(
                Icons.radio_button_unchecked,
                color: Colors.grey.shade300,
                size: 7.w,
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildConfirmButton(
    BuildContext context,
    WidgetRef ref,
    SelectedAddress? selected,
  ) {
    return Container(
      padding: EdgeInsets.all(4.w),
      decoration: const BoxDecoration(
        color: Colors.white,
        boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 4)],
      ),
      child: SafeArea(
        child: SizedBox(
          width: double.infinity,
          child: ElevatedButton(
            onPressed: selected == null
                ? null
                : () {
                    ref.read(selectedAddressProvider.notifier).state = selected;
                    context.pop();
                  },
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColor.primaryColor,
              padding: EdgeInsets.symmetric(vertical: 1.8.h),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(2.5.w),
              ),
              disabledBackgroundColor: Colors.grey.shade300,
            ),
            child: Text(
              "Pilih Alamat Ini",
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
                fontSize: AppFontSize.medium.sp,
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildAddAddressButton(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(4.w),
      child: SafeArea(
        child: SizedBox(
          width: double.infinity,
          child: OutlinedButton.icon(
            onPressed: () => context.pushNamed(AppRoute.mapAddressScreen),
            icon: Icon(
              Icons.add_circle_outline,
              size: 5.w,
              color: AppColor.primaryColor,
            ),
            label: Text(
              "Tambah Alamat Baru",
              style: TextStyle(
                color: AppColor.primaryColor,
                fontWeight: FontWeight.bold,
                fontSize: AppFontSize.medium.sp,
              ),
            ),
            style: OutlinedButton.styleFrom(
              padding: EdgeInsets.symmetric(vertical: 1.8.h),
              side: const BorderSide(color: AppColor.primaryColor),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(2.5.w),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
