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/errors/exceptions.dart';
import 'package:niogu_ecommerce_v1/core/router/app_route.dart';
import 'package:niogu_ecommerce_v1/core/utils/log_message.dart';
import 'package:niogu_ecommerce_v1/core/widgets/custom_snackbar.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 SaveAddressScreen extends ConsumerStatefulWidget {
  final String? label;
  const SaveAddressScreen({super.key, this.label});

  @override
  ConsumerState<SaveAddressScreen> createState() => _SaveAddressScreenState();
}

class _SaveAddressScreenState extends ConsumerState<SaveAddressScreen> {
  late String _selectedLabel;

  @override
  void initState() {
    super.initState();

    _selectedLabel = widget.label ?? 'Rumah';
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> _deleteCustomerAddress() async {
    try {
      final selectedAddress = ref.read(selectedAddressProvider);

      final id = selectedAddress?.id;

      if (id == null) return;

      await ref
          .read(customerControllerProvider.notifier)
          .deleteCustomerAddress(id);

      if (!context.mounted) return;

      CustomSnackbar.showSuccess(context, "Alamat berhasil dihapus");

      await ref.read(customerAddressControllerProvider.notifier).refresh();
      context.pop();
      context.pop();
    } on ServerException catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      CustomSnackbar.showError(context, "Terjadi kesalahan koneksi");
    }
  }

  void _showDeleteConfirmation() {
    final bool isTablet = 100.w >= 600;
    final customerControllerState = ref.watch(customerControllerProvider);
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(4.5.w),
          ),
          elevation: 0,
          backgroundColor: Colors.transparent,
          child: Container(
            padding: EdgeInsets.all(6.w),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(4.5.w),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  padding: EdgeInsets.all(4.w),
                  decoration: BoxDecoration(
                    color: Colors.red[50],
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    Icons.warning_amber_rounded,
                    color: Colors.red,
                    size: 10.w,
                  ),
                ),
                SizedBox(height: 2.h),

                Text(
                  "Hapus Alamat?",
                  style: TextStyle(
                    fontSize: AppFontSize.medium.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
                SizedBox(height: 1.h),
                Text(
                  "Tindakan ini tidak dapat dibatalkan.",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: isTablet
                        ? (AppFontSize.medium - 1.25).sp
                        : (AppFontSize.small - 1.25).sp,
                    color: Colors.grey[600],
                    height: 1.5,
                  ),
                ),
                SizedBox(height: 3.h),

                Row(
                  children: [
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () => Navigator.pop(context),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.grey.shade300,
                          padding: EdgeInsets.symmetric(vertical: 1.5.h),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(2.5.w),
                          ),
                          elevation: 0,
                        ),
                        child: Text(
                          "Batal",
                          style: TextStyle(
                            color: Colors.grey[800],
                            fontWeight: FontWeight.bold,
                            fontSize: AppFontSize.medium.sp,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 3.w),
                    Expanded(
                      child: ElevatedButton(
                        onPressed: customerControllerState.isLoading
                            ? null
                            : _deleteCustomerAddress,
                        style: ElevatedButton.styleFrom(
                          padding: EdgeInsets.symmetric(vertical: 1.5.h),
                          backgroundColor: Colors.red,
                          elevation: 0,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(2.5.w),
                          ),
                          disabledBackgroundColor: Colors.grey.shade300,
                        ),
                        child: Text(
                          "Ya, Hapus",
                          style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: AppFontSize.medium.sp,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Future<void> _saveCustomerAddress() async {
    final selectedAddress = ref.read(selectedAddressProvider);

    if (selectedAddress == null) {
      CustomSnackbar.showError(context, "Tentukan lokasi alamat");
      return;
    }

    final address = CustomerAddress(
      uuid: selectedAddress.id,
      label: _selectedLabel,
      fullAddress: selectedAddress.fullAddress,
      latitude: selectedAddress.latitude,
      longitude: selectedAddress.longitude,
    );
    try {
      await ref
          .read(customerControllerProvider.notifier)
          .saveCustomerAddress(address);

      if (!context.mounted) return;

      CustomSnackbar.showSuccess(context, "Alamat berhasil disimpan");

      await ref.read(customerAddressControllerProvider.notifier).refresh();

      ref.read(selectedAddressProvider.notifier).state = selectedAddress
          .copyWith(label: _selectedLabel);

      context.pop();
    } on ServerException catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      CustomSnackbar.showError(context, "Terjadi kesalahan koneksi");
    }
  }

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

        final customerState = ref.watch(customerControllerProvider);
        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: Colors.white,
            appBar: AppBar(
              backgroundColor: Colors.white,
              elevation: 0,
              centerTitle: true,
              leading: IconButton(
                icon: Icon(
                  Icons.arrow_back,
                  size: 7.w,
                  color: AppColor.primaryColor,
                ),
                onPressed: () => context.pop(),
              ),
              title: Text(
                "Simpan Alamat",
                style: TextStyle(
                  color: Colors.black,
                  fontSize: AppFontSize.medium.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            body: Padding(
              padding: EdgeInsets.all(5.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "Tandai Sebagai :",
                    style: TextStyle(
                      fontSize: AppFontSize.small.sp,
                      fontWeight: FontWeight.bold,
                      color: Colors.grey.shade700,
                    ),
                  ),
                  SizedBox(height: 2.h),
                  Row(
                    children: [
                      _buildLabelOption("Rumah", Icons.home_outlined),
                      SizedBox(width: 4.w),
                      _buildLabelOption("Kantor", Icons.work_outline),
                    ],
                  ),
                  SizedBox(height: 4.h),

                  Text(
                    "Alamat Lengkap",
                    style: TextStyle(
                      fontSize: AppFontSize.small.sp,
                      fontWeight: FontWeight.bold,
                      color: Colors.grey.shade700,
                    ),
                  ),
                  SizedBox(height: 1.5.h),

                  Material(
                    color: Colors.transparent,
                    type: MaterialType.transparency,
                    child: InkWell(
                      onTap: () {
                        context.pushNamed(AppRoute.mapAddressScreen);
                      },
                      child: Container(
                        width: double.infinity,
                        padding: EdgeInsets.symmetric(
                          horizontal: 4.w,
                          vertical: 2.h,
                        ),
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.grey.shade300),
                          borderRadius: BorderRadius.circular(2.05.w),
                        ),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Icon(
                              Icons.map_outlined,
                              color: Colors.black,
                              size: 5.w,
                            ),

                            SizedBox(width: 2.5.w),

                            Expanded(
                              child: Text(
                                selectedAddressState!.fullAddress,
                                style: TextStyle(
                                  fontWeight: FontWeight.normal,
                                  fontSize: AppFontSize.small.sp,
                                  height: 1.4,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),

                  SizedBox(height: 3.h),

                  /**
                  TextField(
                    controller: _addressController,
                    maxLines: 4,
                    decoration: InputDecoration(
                      filled: true,
                      fillColor: Colors.grey.shade50,
                      hintText: "Masukkan detail alamat...",
                      contentPadding: EdgeInsets.all(4.w),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(2.5.w),
                        borderSide: BorderSide(color: Colors.grey.shade200),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(2.5.w),
                        borderSide: BorderSide(color: AppColor.primaryColor),
                      ),
                    ),
                    style: TextStyle(fontSize: (AppFontSize.small - 1).sp),
                  ),
                  const Spacer(),
                  */
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      onPressed: customerState.isLoading
                          ? null
                          : _saveCustomerAddress,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColor.primaryColor,
                        padding: EdgeInsets.symmetric(vertical: 1.8.h),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(2.5.w),
                        ),
                        elevation: 0,
                        disabledBackgroundColor: Colors.grey.shade300,
                      ),
                      child: Text(
                        "Simpan Alamat",
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: AppFontSize.medium.sp,
                        ),
                      ),
                    ),
                  ),
                  if (widget.label != null)
                    Center(
                      child: TextButton.icon(
                        onPressed: _showDeleteConfirmation,
                        style: TextButton.styleFrom(
                          foregroundColor: Colors.red[700],
                          padding: EdgeInsets.symmetric(
                            vertical: 1.5.h,
                            horizontal: 4.w,
                          ),
                        ),
                        icon: Icon(Icons.delete_outline_rounded, size: 5.w),
                        label: Text(
                          "Hapus Alamat Ini",
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: (AppFontSize.small - 1.25).sp,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildLabelOption(String label, IconData icon) {
    bool isSelected = _selectedLabel == label;

    return GestureDetector(
      onTap: () => setState(() => _selectedLabel = label),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 5.w, vertical: 1.2.h),
        decoration: BoxDecoration(
          color: isSelected ? AppColor.primaryColor : Colors.white,
          borderRadius: BorderRadius.circular(2.w),
          border: Border.all(
            color: isSelected ? AppColor.primaryColor : Colors.grey.shade300,
          ),
        ),
        child: Row(
          children: [
            Icon(
              icon,
              color: isSelected ? Colors.white : Colors.grey,
              size: 5.w,
            ),
            SizedBox(width: 2.w),
            Text(
              label,
              style: TextStyle(
                color: isSelected ? Colors.white : Colors.grey,
                fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                fontSize: (AppFontSize.small - 1).sp,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
