import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mighty_school/common/widget/custom_button.dart';
import 'package:mighty_school/common/widget/custom_text_field.dart';
import 'package:mighty_school/common/widget/custom_title.dart';
import 'package:mighty_school/feature/hostel_management/hostel_categories/domain/model/hostel_category_body.dart';
import 'package:mighty_school/feature/hostel_management/hostel_categories/logic/hostel_categories_controller.dart';
import 'package:mighty_school/helper/responsive_helper.dart';
import 'package:mighty_school/util/dimensions.dart';

class AddNewHostelCategoryScreen extends StatefulWidget {
  final int? categoryId;
  const AddNewHostelCategoryScreen({super.key, this.categoryId});

  @override
  State<AddNewHostelCategoryScreen> createState() => _AddNewHostelCategoryScreenState();
}

class _AddNewHostelCategoryScreenState extends State<AddNewHostelCategoryScreen> {
  final TextEditingController nameController = TextEditingController();
  final TextEditingController descriptionController = TextEditingController();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    if (widget.categoryId != null) {
      _loadCategoryData();
    }
  }

  void _loadCategoryData() {
    // If editing, load existing category data
    final categoryController = Get.find<HostelCategoriesController>();
    final category = categoryController.hostelCategoryModel?.data?.data
        ?.firstWhere((cat) => cat.id == widget.categoryId);
    
    if (category != null) {
      nameController.text = category.name ?? '';
      descriptionController.text = category.description ?? '';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      child: SizedBox(
        width: ResponsiveHelper.isDesktop(context) ? 600 : Get.width,
        child: Padding(
          padding: const EdgeInsets.all(Dimensions.paddingSizeDefault),
          child: GetBuilder<HostelCategoriesController>(
            builder: (categoryController) {
              return Form(
                key: formKey,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Title
                    CustomTitle(
                      title: widget.categoryId != null 
                        ? "edit_hostel_category".tr 
                        : "add_new_hostel_category".tr,
                      fontSize: Dimensions.fontSizeLarge,
                    ),
                    
                    const SizedBox(height: Dimensions.paddingSizeDefault),
                    
                    // Name field
                    CustomTextField(
                      controller: nameController,
                      title: "category_name".tr,
                      hintText: "enter_category_name".tr,
                      isRequired: true,
                      validator: (value) {
                        if (value == null || value.trim().isEmpty) {
                          return "please_enter_category_name".tr;
                        }
                        return null;
                      },
                    ),
                    
                    const SizedBox(height: Dimensions.paddingSizeDefault),
                    
                    // Description field
                    CustomTextField(
                      controller: descriptionController,
                      title: "description".tr,
                      hintText: "enter_description".tr,
                      maxLines: 4,
                      validator: (value) {
                        // Description is optional, so no validation needed
                        return null;
                      },
                    ),
                    
                    const SizedBox(height: Dimensions.paddingSizeLarge),
                    
                    // Action buttons
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        // Cancel button
                        TextButton(
                          onPressed: () => Get.back(),
                          child: Text(
                            "cancel".tr,
                            style: TextStyle(
                              color: Theme.of(context).hintColor,
                              fontSize: Dimensions.fontSizeDefault,
                            ),
                          ),
                        ),
                        
                        const SizedBox(width: Dimensions.paddingSizeSmall),
                        
                        // Submit button
                        SizedBox(
                          width: 120,
                          child: CustomButton(
                            text: widget.categoryId != null ? "update".tr : "add".tr,
                            onTap: () => _submitForm(categoryController),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  void _submitForm(HostelCategoriesController categoryController) {
    if (formKey.currentState!.validate()) {
      HostelCategoryBody categoryBody = HostelCategoryBody(
        name: nameController.text.trim(),
        description: descriptionController.text.trim().isEmpty 
          ? null 
          : descriptionController.text.trim(),
      );
      
      if (widget.categoryId != null) {
        categoryController.updateHostelCategory(widget.categoryId!, categoryBody);
      } else {
        categoryController.addNewHostelCategory(categoryBody);
      }
    }
  }
  
  @override
  void dispose() {
    nameController.dispose();
    descriptionController.dispose();
    super.dispose();
  }
}
