import 'dart:io';

import 'package:calendar_date_picker2/calendar_date_picker2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.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/router/app_route.dart';
import 'package:niogu_app/core/enums/campaign_type.dart';
import 'package:niogu_app/core/utils/image_service.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/online_store/domain/entities/online_store.dart';
import 'package:niogu_app/features/online_store/presentation/providers/online_store_provider.dart';
import 'package:niogu_app/features/online_store/presentation/widgets/information_campaign.dart';
import 'package:niogu_app/features/online_store/presentation/widgets/section_campaign_label.dart';
import 'package:niogu_app/core/widgets/custom_selector.dart';
import 'package:niogu_app/features/report/presentation/widgets/filtered_date_range.dart';
import 'package:sizer/sizer.dart';

class AddCampaignScreen extends ConsumerStatefulWidget {
  const AddCampaignScreen({super.key});

  @override
  ConsumerState<AddCampaignScreen> createState() => _AddCampaignScreenState();
}

class _AddCampaignScreenState extends ConsumerState<AddCampaignScreen> {
  final GlobalKey<FormState> _formKey = GlobalKey();

  final TextEditingController _nameController = TextEditingController();

  final ImagePicker _picker = ImagePicker();

  final List<String?> _imagePathTemps = [];

  String? _imagePath;

  List<DateTime?> _initialValue = [
    DateTime.now(),
    DateTime.now().add(const Duration(days: 7)),
  ];

  DateTimeRange? _selectedDateRange;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _nameController.dispose();
    super.dispose();
  }

  String _formatGroupDate(DateTime date) {
    return DateFormat('dd MMMM yyyy').format(date);
  }

  Future<void> _showPickerOptions() async {
    final bool isTablet = 100.w >= 600;
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(2.5.w)),
      ),
      constraints: const BoxConstraints(maxWidth: double.infinity),
      builder: (BuildContext context) {
        return SafeArea(
          child: Container(
            width: 100.w,
            padding: EdgeInsets.symmetric(vertical: 2.h, horizontal: 5.w),
            clipBehavior: Clip.hardEdge,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.vertical(top: Radius.circular(6.w)),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                ListTile(
                  leading: Icon(Icons.photo_library, size: 6.w),
                  title: Text(
                    'Galeri',
                    style: TextStyle(
                      fontSize: isTablet
                          ? AppFontSize.medium.sp
                          : AppFontSize.small.sp,
                    ),
                  ),
                  onTap: () async {
                    await _getImage(ImageSource.gallery);
                    context.pop();
                  },
                ),

                SizedBox(height: 2.h),

                ListTile(
                  leading: Icon(Icons.photo_camera, size: 6.w),
                  title: Text(
                    'Kamera',
                    style: TextStyle(
                      fontSize: isTablet
                          ? AppFontSize.medium.sp
                          : AppFontSize.small.sp,
                    ),
                  ),
                  onTap: () async {
                    await _getImage(ImageSource.camera);
                    context.pop();
                  },
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Future<void> _getImage(ImageSource ImageSource) async {
    try {
      final XFile? pickedFile = await _picker.pickImage(
        source: ImageSource,
        imageQuality: 70,
      );

      if (pickedFile != null) {
        File tempFile = File(pickedFile.path);

        String? imagePath = await ImageService.saveImageToLocalDirectory(
          tempFile,
          "campaign_images",
        );

        if (imagePath != null) {
          _imagePathTemps.add(imagePath);
          setState(() {
            _imagePath = imagePath;
          });
        }
      }
    } catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      CustomSnackbar.showWarning(context, "Akses ditolak");
    }
  }

  Future<void> _cleanUpImages() async {
    for (final image in _imagePathTemps) {
      if (image != null) {
        await ImageService.deleteLocalImage(image);
      }
    }
  }

  Future<void> _showDateRangePicker() async {
    final bool isTablet = 100.w >= 600;

    List<DateTime?> tempSelectedDates = List.from(_initialValue);

    showModalBottomSheet(
      context: context,
      useRootNavigator: true,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      constraints: BoxConstraints(maxWidth: double.infinity),
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setModalState) {
            return Container(
              height: 80.h,
              width: double.infinity,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.vertical(
                  top: Radius.circular(4.5.w),
                ),
              ),
              constraints: BoxConstraints(
                maxHeight: 80.h,
                maxWidth: double.infinity,
              ),
              child: Column(
                children: [
                  SizedBox(height: 1.5.h),
                  Container(
                    width: 12.w,
                    height: 0.6.h,
                    decoration: BoxDecoration(
                      color: Colors.grey[300],
                      borderRadius: BorderRadius.circular(2.5.w),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 2.h),
                    child: Text(
                      "Pilih Rentang Tanggal",
                      style: TextStyle(
                        fontSize: isTablet
                            ? AppFontSize.medium.sp
                            : AppFontSize.small.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Divider(height: 1, color: Colors.grey[200]),

                  Expanded(
                    child: CalendarDatePicker2(
                      config: CalendarDatePicker2Config(
                        calendarType: CalendarDatePicker2Type.range,
                        selectedDayHighlightColor: AppColor.primaryColor,
                        weekdayLabels: [
                          'Min',
                          'Sen',
                          'Sel',
                          'Rab',
                          'Kam',
                          'Jum',
                          'Sab',
                        ],
                        weekdayLabelTextStyle: TextStyle(
                          color: Colors.grey[600],
                          fontWeight: FontWeight.bold,
                          fontSize: isTablet
                              ? AppFontSize.medium.sp
                              : AppFontSize.small.sp,
                        ),
                        controlsTextStyle: TextStyle(
                          color: Colors.black,
                          fontWeight: FontWeight.bold,
                          fontSize: isTablet
                              ? AppFontSize.medium.sp
                              : AppFontSize.small.sp,
                        ),
                        centerAlignModePicker: true,
                        firstDayOfWeek: 1,
                      ),
                      value: tempSelectedDates,
                      onValueChanged: (dates) {
                        setModalState(() {
                          tempSelectedDates = dates;
                        });
                      },
                    ),
                  ),

                  Container(
                    padding: EdgeInsets.all(5.w),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.05),
                          blurRadius: 10,
                          offset: const Offset(0, -5),
                        ),
                      ],
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          child: ElevatedButton(
                            onPressed: () {
                              setState(() {
                                _selectedDateRange = null;
                              });
                              context.pop();
                            },
                            style: ElevatedButton.styleFrom(
                              padding: EdgeInsets.symmetric(vertical: 1.5.h),
                              backgroundColor: Colors.grey.shade300,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(2.5.w),
                              ),
                            ),
                            child: Text(
                              "Atur Ulang",
                              style: TextStyle(
                                color: Colors.black,
                                fontWeight: FontWeight.bold,
                                fontSize: AppFontSize.medium.sp,
                              ),
                            ),
                          ),
                        ),
                        SizedBox(width: 3.w),
                        Expanded(
                          child: ElevatedButton(
                            onPressed: () => context.pop(),
                            style: ElevatedButton.styleFrom(
                              padding: EdgeInsets.symmetric(vertical: 1.5.h),
                              backgroundColor: Colors.grey.shade500,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(2.5.w),
                              ),
                            ),
                            child: Text(
                              "Batal",
                              style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                                fontSize: AppFontSize.medium.sp,
                              ),
                            ),
                          ),
                        ),
                        SizedBox(width: 3.w),
                        Expanded(
                          child: ElevatedButton(
                            onPressed: tempSelectedDates.length < 2
                                ? null
                                : () {
                                    _initialValue = tempSelectedDates;
                                    final startDate = tempSelectedDates[0]!;

                                    final endDate = tempSelectedDates[1]!;

                                    final dateRange = DateTimeRange(
                                      start: startDate,
                                      end: endDate,
                                    );

                                    setState(() {
                                      _selectedDateRange = dateRange;
                                    });
                                    context.pop();
                                  },
                            style: ElevatedButton.styleFrom(
                              padding: EdgeInsets.symmetric(vertical: 1.5.h),
                              backgroundColor: AppColor.primaryColor,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(2.5.w),
                              ),
                              disabledBackgroundColor: Colors.grey.shade300,
                            ),
                            child: Text(
                              "Pilih",
                              style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                                fontSize: AppFontSize.medium.sp,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }

  Future<void> _saveCampaign() async {
    if (_imagePath == null) {
      CustomSnackbar.showError(context, "Tambahkan gambar campaign");
      return;
    }

    if (!_formKey.currentState!.validate()) return;

    final selectedTargetOutlets = ref.read(
      selectedTargetOutletControllerProvider,
    );

    if (selectedTargetOutlets.isEmpty) {
      CustomSnackbar.showError(context, "Tentukan tujuan campaign");
      return;
    }

    final selectedCampaignItem = ref.read(selectedCampaignItemProvider);

    final targetOutlets = selectedTargetOutlets.values.map((outlet) {
      return UpsertTargetOutlet(outletId: outlet.outletId);
    }).toList();

    try {
      await ref
          .read(onlineStoreControllerProvider.notifier)
          .saveCampaign(
            campaign: UpsertCampaign(
              imagePath: _imagePath!,
              name: _nameController.text.trim(),
              startDate: _selectedDateRange?.start,
              endDate: _selectedDateRange?.end,
              campaignType: selectedCampaignItem?.type,
              linkId: selectedCampaignItem?.id,
              targetOutlets: targetOutlets,
            ),
          );

      if (!mounted) return;

      CustomSnackbar.showSuccess(context, "Campaign baru berhasil dibuat");
      context.pop();
    } catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      CustomSnackbar.showError(context, "Ups, terjadi kesalahan");
    }
  }

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

        final File imageFile = File(_imagePath ?? "image not found");

        final bool imageFileExists = imageFile.existsSync();

        final selectedItemCampaignState = ref.watch(
          selectedCampaignItemProvider,
        );

        final type = selectedItemCampaignState?.type == CampaignType.product
            ? "Produk"
            : "Kategori";

        final linkName = "${selectedItemCampaignState?.name} ($type)";

        String? targetName;

        final selectedTargetOutletControllerState = ref.watch(
          selectedTargetOutletControllerProvider,
        );

        if (selectedTargetOutletControllerState.isNotEmpty) {
          if (selectedTargetOutletControllerState.values.length > 1) {
            targetName =
                selectedTargetOutletControllerState.values.first.name +
                " +${selectedTargetOutletControllerState.values.length - 1} lainnya";
          } else {
            targetName = selectedTargetOutletControllerState.values.first.name;
          }
        }

        final onlineStoreControllerState = ref.watch(
          onlineStoreControllerProvider,
        );

        return PopScope(
          canPop: false,
          onPopInvokedWithResult: (didPop, result) async {
            if (didPop) return;

            await _cleanUpImages();

            context.pop();
          },
          child: SafeArea(
            top: false,
            bottom: true,
            right: false,
            left: false,
            child: Scaffold(
              backgroundColor: const Color(0xFFF9FAFB),
              appBar: TopBackBarApp(
                title: "Buat Campaign Baru",
                onTap: () async {
                  await _cleanUpImages();

                  context.pop();
                },
              ),
              body: SingleChildScrollView(
                padding: EdgeInsets.all(5.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SectionCampaignLabel(
                      isTablet: isTablet,
                      label: "Banner Campaign (Landscape)",
                    ),
                    Stack(
                      clipBehavior: Clip.none,
                      children: [
                        Container(
                          height: 20.h,
                          width: double.infinity,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(3.w),
                            border: Border.all(
                              color: Colors.grey.shade300,
                              style: BorderStyle.solid,
                            ),
                          ),
                          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,
                                      );
                                    },
                                  ),
                                )
                              : GestureDetector(
                                  onTap: _showPickerOptions,
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Icon(
                                        Icons.add_photo_alternate_outlined,
                                        color: Colors.grey.shade700,
                                        size: 10.w,
                                      ),

                                      SizedBox(height: 0.75.h),

                                      Text(
                                        "Ketuk untuk unggah banner",
                                        style: TextStyle(
                                          fontSize: isTablet
                                              ? (AppFontSize.medium - 1.25).sp
                                              : (AppFontSize.small - 1.25).sp,
                                          color: Colors.grey.shade700,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                        ),

                        if (_imagePath != null)
                          Positioned(
                            top: 1.w,
                            right: 1.w,
                            child: Material(
                              color: Colors.transparent,
                              type: MaterialType.transparency,
                              child: InkWell(
                                onTap: () {
                                  setState(() {
                                    _imagePath = null;
                                  });
                                },
                                child: Container(
                                  padding: EdgeInsets.all(1.w),
                                  decoration: BoxDecoration(
                                    color: Colors.red[50],
                                    shape: BoxShape.circle,
                                    border: Border.all(
                                      color: Colors.red.withOpacity(0.2),
                                    ),
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.black.withOpacity(0.1),
                                        blurRadius: 2,
                                        offset: Offset(0, 1),
                                      ),
                                    ],
                                  ),
                                  child: Icon(
                                    Icons.remove,
                                    color: Colors.red,
                                    size: 4.w,
                                  ),
                                ),
                              ),
                            ),
                          ),
                      ],
                    ),
                    SizedBox(height: 3.h),

                    Form(
                      key: _formKey,
                      child: CustomTextFormField(
                        label: "Nama Campaign",
                        hint: "Contoh: Promo Gajian",
                        controller: _nameController,
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return "Nama campaign belum diisi";
                          }

                          return null;
                        },
                      ),
                    ),
                    SizedBox(height: 2.h),
                    InformationCampaign(
                      isTablet: isTablet,
                      information:
                          "Masa berlaku yang ditampikan di toko online (opsional)",
                    ),
                    FilteredDateRange(
                      value: _selectedDateRange == null
                          ? "Pilih Masa Durasi"
                          : "${_formatGroupDate(_selectedDateRange!.start)} - ${_formatGroupDate(_selectedDateRange!.end)}",
                      onTap: _showDateRangePicker,
                    ),

                    SizedBox(height: 3.h),

                    SectionCampaignLabel(
                      isTablet: isTablet,
                      label: "Tautkan Campaign",
                    ),
                    InformationCampaign(
                      isTablet: isTablet,
                      information:
                          "Tautkan ke kategori atau produk tertentu (opsional)",
                    ),
                    CustomSelector(
                      isTablet: isTablet,
                      title: selectedItemCampaignState == null
                          ? "Pilih Kategori Atau Produk"
                          : linkName,
                      onTap: () {
                        context.pushNamed(AppRoute.linkCampaignScreen);
                      },
                    ),
                    SizedBox(height: 3.h),

                    SectionCampaignLabel(
                      isTablet: isTablet,
                      label: "Tujuan Campaign",
                    ),
                    InformationCampaign(
                      isTablet: isTablet,
                      information: "Tentukan outlet yang menampilkan",
                    ),
                    CustomSelector(
                      isTablet: isTablet,
                      title: targetName == null ? "Pilih Outlet" : targetName,
                      onTap: () {
                        context.pushNamed(AppRoute.targetOutletScreen);
                      },
                    ),
                    SizedBox(height: 2.h),
                    ElevatedButton(
                      onPressed: onlineStoreControllerState.isLoading
                          ? null
                          : _saveCampaign,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColor.primaryColor,
                        minimumSize: Size(double.infinity, 7.h),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(3.w),
                        ),
                      ),
                      child: Text(
                        "Simpan",
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: AppFontSize.medium.sp,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
