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/constants/app_font_size.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 AddProductCategoryScreen extends ConsumerStatefulWidget {
  const AddProductCategoryScreen({super.key});

  @override
  ConsumerState<AddProductCategoryScreen> createState() =>
      _AddProductCategoryScreenState();
}

class _AddProductCategoryScreenState
    extends ConsumerState<AddProductCategoryScreen> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  final TextEditingController _nameController = TextEditingController();

  final ImagePicker _picker = ImagePicker();

  bool _canPop = false;

  String? _categoryImage;

  String? _pathImageTemp;

  Timer? _debounce;

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

  @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 {
    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> _addCategory(Category category) async {
    try {
      await ref.read(categoryControllerProvider.notifier).addCategory(category);

      if (!mounted) return;

      CustomSnackbar.showSuccess(context, "Kategori berhasil disimpan");
      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(4.w)),
        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),

                  Text(
                    "Foto Kategori (Opsional)",
                    style: TextStyle(
                      fontSize: isTablet
                          ? AppFontSize.medium.sp
                          : AppFontSize.small.sp,
                      fontWeight: FontWeight.bold,
                      color: Colors.black87,
                    ),
                  ),

                  SizedBox(height: 1.h),

                  ImageUploaderProductCategory(
                    categoryImage: _categoryImage,
                    onTapCategoryImageAdd: _getImage,
                    onTapCategoryImageRemove: _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)) {
                              final category = Category(
                                name: _nameController.text.trim(),
                                imagePath: _categoryImage,
                              );

                              await _addCategory(category);
                            }
                          },
                  ),

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