import 'dart:async';
import 'dart:io';

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:niogu_app/core/utils/image_service.dart';
import 'package:niogu_app/core/utils/log_message.dart';
import 'package:niogu_app/core/widgets/custom_button.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/goods/products/domain/entities/category.dart';
import 'package:niogu_app/features/goods/products/presentation/providers/category_provider.dart';
import 'package:niogu_app/features/goods/products/presentation/widgets/image_uploader_product_category.dart';
import 'package:sizer/sizer.dart';

class EditProductCategoryScreen extends ConsumerStatefulWidget {
  final Category category;

  const EditProductCategoryScreen({super.key, required this.category});

  @override
  ConsumerState<EditProductCategoryScreen> createState() =>
      _EditProductCategoryScreenState();
}

class _EditProductCategoryScreenState
    extends ConsumerState<EditProductCategoryScreen> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  final TextEditingController _nameController = TextEditingController();

  final ImagePicker _picker = ImagePicker();

  bool _canPop = false;

  String? _categoryImage;

  String? _pathImageRemove;

  String? _pathImageTemp;

  Timer? _debounce;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _categoryImage = widget.category.imagePath;
    _nameController.text = widget.category.name;
  }

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

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

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

        String? savedPath = await ImageService.saveImageToLocalDirectory(
          tempFile,
          "product_category_images",
        );

        if (savedPath != null) {
          _pathImageTemp = savedPath;
          setState(() {
            _categoryImage = savedPath;
          });
        }
      }
    } catch (e, st) {
      LogMessage.log.w(e.toString(), error: e, stackTrace: st);
      CustomSnackbar.showWarning(context, "Akses ditolak");
    }
  }

  Future<void> _removeImage() async {
    _pathImageRemove = _categoryImage;
    setState(() {
      _categoryImage = null;
    });
  }

  Future<void> _cleanUpImages() async {
    if (_pathImageTemp != null && _pathImageTemp!.isNotEmpty) {
      await ImageService.deleteLocalImage(_pathImageTemp!);
    }
  }

  void _onChanged(String value) {
    if (_debounce?.isActive ?? false) _debounce!.cancel();

    _debounce = Timer(const Duration(milliseconds: 500), () async {
      if (value.isEmpty) return;

      ref.read(categorySearchProvider.notifier).state = value;
    });
  }

  Future<void> _onCancel() async {
    await _cleanUpImages();

    if (mounted) {
      setState(() {
        _canPop = true;
      });
      context.pop();
    }
  }

  Future<void> _updateCategory(
    String id,
    String name,
    String? imagePath,
  ) async {
    if (_pathImageRemove != null && _pathImageRemove!.isNotEmpty) {
      await ImageService.deleteLocalImage(_pathImageRemove!);
    }

    try {
      await ref
          .read(categoryControllerProvider.notifier)
          .updateCategory(id, name, imagePath);

      if (!mounted) return;

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

  @override
  Widget build(BuildContext context) {
    final bool isTablet = 100.w >= 600;

    final double maxWidth = 100.w >= 1280
        ? 1200
        : isTablet
        ? 800
        : 400;
    final validateCategory = ref.watch(validateCategoryProvider);

    final categoryControllerState = ref.watch(categoryControllerProvider);

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

        await _onCancel();
      },
      child: Dialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
        backgroundColor: Colors.white,
        child: Form(
          key: _formKey,
          child: Container(
            padding: EdgeInsets.all(5.w),
            constraints: BoxConstraints(maxWidth: maxWidth),
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  SizedBox(height: 1.h),

                  ImageUploaderProductCategory(
                    categoryImage: _categoryImage,
                    onTapCategoryImageAdd: () async => await _getImage(),
                    onTapCategoryImageRemove: () async => await _removeImage(),
                  ),

                  SizedBox(height: 3.h),

                  CustomTextFormField(
                    label: "Nama Kategori",
                    hint: "Contoh : Snack",
                    controller: _nameController,
                    validator: (value) {
                      if (value == null || value.trim().isEmpty) {
                        return "Nama kategori belum diisi";
                      }

                      return null;
                    },
                    errorText: validateCategory
                        ? null
                        : "Kategori ini telah tersedia",
                    onChanged: (value) => _onChanged(value),
                  ),

                  SizedBox(height: 3.h),

                  CustomButton(
                    title: "Simpan",
                    onPressed: categoryControllerState.isLoading
                        ? null
                        : () async {
                            if (_formKey.currentState!.validate() &&
                                ref.read(validateCategoryProvider)) {
                              await _updateCategory(
                                widget.category.id,
                                _nameController.text.trim(),
                                _categoryImage,
                              );
                            }
                          },
                  ),

                  SizedBox(height: 1.h),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
