import 'dart:io';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter_remix/flutter_remix.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:lottie/lottie.dart';
import 'package:venderfoodyman/presentation/component/components.dart';
import 'package:venderfoodyman/presentation/pages/auth/become_seller/widgets/set_background_image.dart';
import '../../../../application/profile/profile_notifier.dart';
import '../../../../application/profile/profile_provider.dart';
import '../../../../infrastructure/services/app_helpers.dart';
import '../../../../infrastructure/services/local_storage.dart';
import '../../../../infrastructure/services/tr_keys.dart';
import '../../../component/text_fields/outline_bordered_text_field.dart';
import '../../../routes/app_router.gr.dart';
import '../../../styles/style.dart';
import '../../shop/widgets/logout_modal.dart';

class CreateShopPage extends ConsumerStatefulWidget {
  const CreateShopPage({Key? key}) : super(key: key);

  @override
  ConsumerState<CreateShopPage> createState() => _EditRestaurantState();
}

class _EditRestaurantState extends ConsumerState<CreateShopPage> {
  late ProfileNotifier event;
  late TextEditingController shopName;
  late TextEditingController descName;
  late TextEditingController phoneName;
  late TextEditingController tax;
  late TextEditingController deliveryTimeFrom;
  late TextEditingController deliveryTimeTo;
  late TextEditingController startPrice;
  late TextEditingController pricePerKm;
  dynamic data;

  List list = ["minute", "day", "month"];

  String value = "minute";

  @override
  void initState() {
    shopName = TextEditingController();
    descName = TextEditingController();
    phoneName = TextEditingController();
    deliveryTimeFrom = TextEditingController();
    deliveryTimeTo = TextEditingController();
    startPrice = TextEditingController();
    pricePerKm = TextEditingController();
    tax = TextEditingController();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(profileProvider.notifier).resetShopData();
      ref.read(profileProvider.notifier).fetchUser(context, onSuccess: (phone) {
        phoneName.text = phone ?? '';
      });
    });
    super.initState();
  }

  @override
  void didChangeDependencies() {
    event = ref.read(profileProvider.notifier);
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    shopName.dispose();
    descName.dispose();
    phoneName.dispose();
    deliveryTimeFrom.dispose();
    deliveryTimeTo.dispose();
    startPrice.dispose();
    pricePerKm.dispose();
    tax.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(profileProvider);
    return KeyboardDisable(
      child: Scaffold(
        backgroundColor: Style.white,
        body: Column(
          children: [
            CustomAppBar(
              bottomPadding: 16,
              child: Text(
                AppHelpers.trans(TrKeys.becomeSeller),
                style: Style.interSemi(
                  size: 18,
                  color: Style.blackColor,
                ),
              ),
            ),
            state.isLoading
                ? const Expanded(child: Loading())
                : state.userData?.shop?.status == "new"
                    ? Expanded(
                        child: Column(
                          children: [
                            Lottie.asset('assets/lottie/processing.json'),
                            Text(
                              AppHelpers.trans(
                                TrKeys.yourRequest,
                              ),
                              style: Style.interNormal(
                                size: 18,
                                color: Style.blackColor,
                              ),
                            ),
                            const Spacer(),
                            Padding(
                              padding: REdgeInsets.all(24),
                              child: CustomButton(
                                title: AppHelpers.trans(TrKeys.logOut),
                                onPressed: () =>
                                    AppHelpers.showCustomModalBottomSheet(
                                  context: context,
                                  modal: const LogoutModal(),
                                  isDarkMode:
                                      LocalStorage.instance.getAppThemeMode(),
                                ),
                              ),
                            ),
                          ],
                        ),
                      )
                    : state.userData?.shop?.status == 'rejected'
                        ? Expanded(
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                const Spacer(),
                                Lottie.asset('assets/lottie/close.json'),
                                48.verticalSpace,
                                Text(
                                  AppHelpers.trans(
                                    TrKeys.yourShopRejected,
                                  ),
                                  style: Style.interNormal(
                                    size: 18,
                                    color: Style.blackColor,
                                  ),
                                ),
                                const Spacer(),
                                Padding(
                                  padding: REdgeInsets.all(24),
                                  child: CustomButton(
                                    isLoading: state.deleteLoading,
                                      title:
                                          AppHelpers.trans(TrKeys.recreateShop),
                                      onPressed: () {
                                        event..deleteShopInvitation(
                                          invitationId: state.userData?.invitation?.id,
                                        )..deleteShop();
                                      }),
                                ),
                                Padding(
                                  padding: REdgeInsets.symmetric(horizontal: 24),
                                  child: CustomButton(
                                    title: AppHelpers.trans(TrKeys.logOut),
                                    onPressed: () =>
                                        AppHelpers.showCustomModalBottomSheet(
                                      context: context,
                                      modal: const LogoutModal(),
                                      isDarkMode: LocalStorage.instance
                                          .getAppThemeMode(),
                                    ),
                                  ),
                                ),
                                24.verticalSpace
                              ],
                            ),
                          )
                        : Expanded(
                            child: Padding(
                              padding: EdgeInsets.symmetric(horizontal: 16.w),
                              child: Column(
                                children: [
                                  16.verticalSpace,
                                  Expanded(
                                    child: ListView(
                                      physics: const BouncingScrollPhysics(),
                                      padding: EdgeInsets.zero,
                                      shrinkWrap: true,
                                      children: [
                                        Column(
                                          children: [
                                            const SetBackgroundImage(),
                                            24.verticalSpace,
                                            Row(
                                              children: [
                                                InkWell(
                                                  onTap: () async {
                                                    XFile? file;
                                                    try {
                                                      file = await ImagePicker()
                                                          .pickImage(
                                                              source:
                                                                  ImageSource
                                                                      .gallery);
                                                    } catch (ex) {
                                                      debugPrint(
                                                          '===> trying to select image $ex');
                                                    }
                                                    if (file != null) {
                                                      event.setLogoImage(
                                                          file.path);
                                                    }
                                                  },
                                                  child: Container(
                                                    width: 50.r,
                                                    height: 50.r,
                                                    padding:
                                                        EdgeInsets.all(6.r),
                                                    decoration: state.logoImage
                                                            .isNotEmpty
                                                        ? BoxDecoration(
                                                            color: Style
                                                                .blackColor
                                                                .withOpacity(
                                                                    0.27),
                                                            borderRadius:
                                                                BorderRadius
                                                                    .circular(
                                                                        16.r),
                                                            image: DecorationImage(
                                                                image: FileImage(
                                                                    File(state
                                                                        .logoImage)),
                                                                fit: BoxFit
                                                                    .cover),
                                                          )
                                                        : BoxDecoration(
                                                            color: Style
                                                                .blackColor
                                                                .withOpacity(
                                                                    0.27),
                                                            borderRadius:
                                                                BorderRadius
                                                                    .circular(
                                                                        16.r),
                                                          ),
                                                    child: const Center(
                                                      child: Icon(
                                                        FlutterRemix
                                                            .camera_fill,
                                                        color: Style.white,
                                                      ),
                                                    ),
                                                  ),
                                                ),
                                                16.horizontalSpace,
                                                Expanded(
                                                  child:
                                                      OutlinedBorderTextField(
                                                    textController: shopName,
                                                    label: AppHelpers.trans(
                                                      TrKeys.restaurantName,
                                                    ),
                                                  ),
                                                ),
                                              ],
                                            ),
                                            24.verticalSpace,
                                            OutlinedBorderTextField(
                                              textController: descName,
                                              label: AppHelpers.trans(
                                                  TrKeys.description),
                                            ),
                                            24.verticalSpace,
                                            OutlinedBorderTextField(
                                              textController: phoneName,
                                              inputType: TextInputType.phone,
                                              label: AppHelpers.trans(
                                                  TrKeys.phoneNumber),
                                            ),
                                            24.verticalSpace,
                                            OutlinedBorderTextField(
                                              textController: tax,
                                              inputType: TextInputType.number,
                                              label:
                                                  AppHelpers.trans(TrKeys.tax),
                                            ),
                                            24.verticalSpace,
                                            DropdownButtonFormField(
                                              value: value,
                                              items: list
                                                  .map((e) => DropdownMenuItem(
                                                      value: e, child: Text(e)))
                                                  .toList(),
                                              onChanged: (s) {
                                                if (s != null) {
                                                  value = s.toString();
                                                }
                                              },
                                              decoration: InputDecoration(
                                                labelText: AppHelpers.trans(
                                                    TrKeys.deliveryType),
                                                labelStyle: Style.interNormal(
                                                  size: 12,
                                                  color: Style.blackColor,
                                                ),
                                                enabledBorder: UnderlineInputBorder(
                                                    borderSide: BorderSide.merge(
                                                        const BorderSide(
                                                            color: Style
                                                                .differBorderColor),
                                                        const BorderSide(
                                                            color: Style
                                                                .differBorderColor))),
                                                errorBorder: InputBorder.none,
                                                border:
                                                    const UnderlineInputBorder(),
                                                focusedErrorBorder:
                                                    const UnderlineInputBorder(),
                                                disabledBorder: UnderlineInputBorder(
                                                    borderSide: BorderSide.merge(
                                                        const BorderSide(
                                                            color: Style
                                                                .differBorderColor),
                                                        const BorderSide(
                                                            color: Style
                                                                .differBorderColor))),
                                                focusedBorder:
                                                    const UnderlineInputBorder(),
                                              ),
                                            ),
                                            24.verticalSpace,
                                            OutlinedBorderTextField(
                                              textController: deliveryTimeFrom,
                                              inputType: TextInputType.number,
                                              label: AppHelpers.trans(
                                                  TrKeys.deliveryTimeFrom),
                                            ),
                                            24.verticalSpace,
                                            OutlinedBorderTextField(
                                              inputType: TextInputType.number,
                                              textController: deliveryTimeTo,
                                              label: AppHelpers.trans(
                                                  TrKeys.deliveryTimeTo),
                                            ),
                                            24.verticalSpace,
                                            OutlinedBorderTextField(
                                              textController: startPrice,
                                              inputType: TextInputType.number,
                                              label: AppHelpers.trans(
                                                  TrKeys.startPrice),
                                            ),
                                            24.verticalSpace,
                                            OutlinedBorderTextField(
                                              inputType: TextInputType.number,
                                              textController: pricePerKm,
                                              label: AppHelpers.trans(
                                                  TrKeys.pricePerKm),
                                            ),
                                          ],
                                        ),
                                        24.verticalSpace,
                                        const Divider(),
                                        GestureDetector(
                                          onTap: () async {
                                            data = await context.pushRoute(
                                                ViewMapRoute(
                                                    isShopLocation: true,
                                                    onChanged: () {}));
                                            event.setAddress(data);
                                          },
                                          child: Container(
                                            color: Style.transparent,
                                            child: Padding(
                                              padding: EdgeInsets.all(16.r),
                                              child: Row(
                                                children: [
                                                  Icon(
                                                    FlutterRemix
                                                        .navigation_fill,
                                                    size: 20.r,
                                                  ),
                                                  8.horizontalSpace,
                                                  Column(
                                                    crossAxisAlignment:
                                                        CrossAxisAlignment
                                                            .start,
                                                    children: [
                                                      Text(
                                                        AppHelpers.trans(
                                                            TrKeys.address),
                                                        style: Style.interNormal(
                                                            size: 12.sp,
                                                            color: Style
                                                                .blackColor),
                                                      ),
                                                      SizedBox(
                                                        width: MediaQuery.of(
                                                                    context)
                                                                .size
                                                                .width /
                                                            2,
                                                        child: Text(
                                                          state.addressModel
                                                                  ?.title ??
                                                              AppHelpers.trans(
                                                                  TrKeys
                                                                      .selectedAddress),
                                                          style: Style.interNormal(
                                                              size: 12.sp,
                                                              color: Style
                                                                  .blackColor),
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                  const Spacer(),
                                                  const Icon(FlutterRemix
                                                      .arrow_right_s_line)
                                                ],
                                              ),
                                            ),
                                          ),
                                        ),
                                        const Divider(),
                                        24.verticalSpace,
                                        Padding(
                                          padding:
                                              EdgeInsets.only(bottom: 32.h),
                                          child: CustomButton(
                                            isLoading: state.isSaveLoading,
                                            title:
                                                AppHelpers.trans(TrKeys.save),
                                            onPressed: () {
                                              event.createShop(
                                                context: context,
                                                tax: tax.text,
                                                deliveryTo: deliveryTimeTo.text,
                                                deliveryFrom:
                                                    deliveryTimeFrom.text,
                                                phone: phoneName.text,
                                                startPrice: startPrice.text,
                                                name: shopName.text,
                                                desc: descName.text,
                                                perKm: pricePerKm.text,
                                                address: data,
                                                deliveryType: value,
                                                categoryId: 1,
                                              );
                                            },
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
          ],
        ),
      ),
    );
  }
}
