import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.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/units/domain/entities/unit.dart';
import 'package:niogu_app/features/goods/units/presentation/providers/unit_provider.dart';
import 'package:sizer/sizer.dart';

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

  @override
  ConsumerState<AddUnitScreen> createState() => _AddUnitScreenState();
}

class _AddUnitScreenState extends ConsumerState<AddUnitScreen> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController _nameController = TextEditingController();

  Timer? _debounce;

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

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

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

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

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

  Future<void> _addUnit(Unit unit) async {
    try {
      await ref.read(unitControllerProvider.notifier).addUnit(unit);

      if(!mounted) return;

      CustomSnackbar.showSuccess(context, "Satuan 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 validateUnit = ref.watch(validateUnitProvider);

    final unitControllerState = ref.watch(unitControllerProvider);

    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4.w)),
      backgroundColor: Colors.white,
      child: Container(
        padding: EdgeInsets.all(5.w),
        constraints: BoxConstraints(maxWidth: maxWidth),
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(height: 2.h),

              CustomTextFormField(
                label: "Nama Satuan",
                hint: "Contoh : Kg",
                controller: _nameController,
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return "Nama satuan belum diisi";
                  }
                  return null;
                },
                errorText: validateUnit ? null : "Satuan ini telah tersedia",
                onChanged: (value) => _onChanged(value),
              ),

              SizedBox(height: 3.h),

              CustomButton(
                title: "Simpan",
                onPressed: unitControllerState.isLoading
                    ? null
                    : () async {
                        if (_formKey.currentState!.validate() &&
                            ref.read(validateUnitProvider)) {
                          await _addUnit(
                            Unit(name: _nameController.text.trim()),
                          );
                        }
                      },
              ),
              SizedBox(height: 1.h),
            ],
          ),
        ),
      ),
    );
  }
}
