import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/components/top_back_bar_app.dart';
import 'package:niogu_app/core/constants/app_color.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/providers/app_provider.dart';
import 'package:niogu_app/core/router/app_route.dart';
import 'package:niogu_app/core/utils/log_message.dart';
import 'package:niogu_app/core/widgets/custom_snackbar.dart';
import 'package:niogu_app/core/widgets/custom_text_form_field.dart';
import 'package:niogu_app/features/outlets/domain/entities/outlet.dart';
import 'package:niogu_app/features/outlets/presentation/providers/outlet_provider.dart';
import 'package:niogu_app/features/profile/domain/entities/profile.dart';
import 'package:sizer/sizer.dart';

class OutletInfoScreen extends ConsumerWidget {
  final OutletInfo outletInfo;
  const OutletInfoScreen({super.key, required this.outletInfo});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final bool isTablet = 100.w >= 600;

        final File imageFile = File(outletInfo.imagePath ?? "image not found");

        final bool imageFileExists = imageFile.existsSync();

        final outletControllerState = ref.watch(outletControllerProvider);

        final mapOutletAddressState = ref.watch(mapOutletAddressProvider);

        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: Colors.white,
            appBar: TopBackBarApp(
              title: "Informasi Outlet",
              onTap: () => context.pop(),
            ),
            body: SingleChildScrollView(
              padding: EdgeInsets.all(5.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: EdgeInsets.only(bottom: 1.5.h),
                    child: Text(
                      "Foto Outlet",
                      style: TextStyle(
                        fontSize: (AppFontSize.medium - 1.25).sp,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                  ),

                  Container(
                    height: 20.h,
                    width: double.infinity,
                    decoration: BoxDecoration(
                      color: Colors.grey.shade100,
                      borderRadius: BorderRadius.circular(3.w),
                      border: Border.all(
                        color: Colors.grey.shade300,
                        style: BorderStyle.none,
                      ),
                    ),
                    child: imageFileExists
                        ? ClipRRect(
                            borderRadius: BorderRadius.circular(2.5.w),
                            child: Image.file(
                              imageFile,
                              fit: BoxFit.cover,
                              width: double.infinity,
                              height: double.infinity,
                              errorBuilder: (context, error, stackTrace) {
                                return Icon(
                                  Icons.error,
                                  color: Colors.grey[400],
                                  size: 10.w,
                                );
                              },
                            ),
                          )
                        : Icon(
                            Icons.store_outlined,
                            size: 10.w,
                            color: Colors.grey.shade700,
                          ),
                  ),

                  SizedBox(height: 3.h),

                  CustomTextFormField(
                    label: "Nama Usaha",
                    prefixIcon: Icons.store_mall_directory_outlined,
                    controller: TextEditingController(
                      text: outletInfo.tenantName,
                    ),
                    readOnly: true,
                  ),
                  SizedBox(height: 3.h),

                  CustomTextFormField(
                    label: "Nama Outlet",
                    hint: '-',
                    prefixIcon: Icons.store_mall_directory_outlined,
                    controller: TextEditingController(text: outletInfo.name),
                    readOnly: true,
                  ),
                  SizedBox(height: 3.h),

                  CustomTextFormField(
                    label: "No. Handphone / WA Outlet",
                    prefixIcon: Icons.phone_android_outlined,
                    controller: TextEditingController(
                      text: outletInfo.phoneNumber,
                    ),
                    keyboardType: TextInputType.phone,
                    readOnly: true,
                  ),
                  SizedBox(height: 3.h),
                  CustomTextFormField(
                    label: "Email",
                    hint: "-",
                    prefixIcon: Icons.email_outlined,
                    keyboardType: TextInputType.emailAddress,
                    controller: TextEditingController(text: outletInfo.email),
                    readOnly: true,
                  ),
                  SizedBox(height: 3.h),

                  Material(
                    color: Colors.transparent,
                    type: MaterialType.transparency,
                    child: InkWell(
                      onTap: () {
                        context.pushNamed(AppRoute.mapOutletAdressScreen);
                      },
                      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(
                                mapOutletAddressState != null
                                    ? mapOutletAddressState.fullAddress
                                    : "Atur alamat outlet",
                                style: TextStyle(
                                  fontWeight: mapOutletAddressState != null
                                      ? FontWeight.normal
                                      : FontWeight.bold,
                                  fontSize: isTablet
                                      ? AppFontSize.medium.sp
                                      : AppFontSize.small.sp,
                                  height: 1.4,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),

                  SizedBox(height: 3.h),

                  ElevatedButton(
                    onPressed: outletControllerState.isLoading
                        ? null
                        : () async {
                            final selectedOutletAddress = ref.read(
                              mapOutletAddressProvider,
                            );

                            final currentOutletId = ref.read(
                              currentOutletIdProvider,
                            );

                            final upsertOutlet = UpsertOutlet(
                              id: currentOutletId,
                              bannerPath: outletInfo.imagePath,
                              name: outletInfo.name,
                              phoneNumber: outletInfo.phoneNumber,
                              email: outletInfo.email,
                              fullAddress: selectedOutletAddress?.fullAddress,
                              latitude: selectedOutletAddress
                                  ?.currentLocation
                                  .latitude,
                              longitude: selectedOutletAddress
                                  ?.currentLocation
                                  .longitude,
                            );

                            try {
                              await ref
                                  .read(outletControllerProvider.notifier)
                                  .saveOutlet(upsertOutlet);

                              if (!context.mounted) return;

                              CustomSnackbar.showSuccess(
                                context,
                                'Outlet baru berhasil ditambahkan',
                              );
                              context.pop();
                            } catch (e, st) {
                              LogMessage.log.e(
                                e.toString(),
                                error: e,
                                stackTrace: st,
                              );
                              CustomSnackbar.showError(
                                context,
                                'Ups, terjadi kesalahan',
                              );
                            }
                          },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppColor.primaryColor,
                      minimumSize: Size(double.infinity, 7.h),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(3.w),
                      ),
                      disabledBackgroundColor: Colors.grey.shade300,
                    ),
                    child: Text(
                      "Simpan",
                      style: TextStyle(
                        fontSize: AppFontSize.medium.sp,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  SizedBox(height: 3.h),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
