import 'package:hmg_patient_app/core/model/hospitals/hospitals_model.dart';
import 'package:hmg_patient_app/core/viewModels/medical/radiology_view_model.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/widgets/buttons/defaultButton.dart';
import 'package:flutter/material.dart';

import '../../uitl/translations_delegate_base.dart';

class LocationSelectionDialog extends StatelessWidget {
  final List<HospitalsModel> data;
  final Function(int)? onValueSelected;
  final int? selectedIndex;
  final bool isArabic;

  const LocationSelectionDialog({super.key, required this.data, this.onValueSelected, this.selectedIndex, required this.isArabic});

  @override
  Widget build(BuildContext context) {
    return Dialog(
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        child: LocationDialogBody(
          isArabic: isArabic,
          data: data,
          onValueSelected: onValueSelected,
          selectedIndex: selectedIndex,
        ));
  }
}

class LocationDialogBody extends StatefulWidget {
  final List<HospitalsModel> data;
  final Function(int)? onValueSelected;
  final int? selectedIndex;
  final bool isArabic;

  const LocationDialogBody({super.key, required this.data, this.onValueSelected, this.selectedIndex, required this.isArabic});

  @override
  State<LocationDialogBody> createState() => _LocationDialogBodyState();
}

class _LocationDialogBodyState extends State<LocationDialogBody> {
  bool isListVisible = false;
  int currentlySelected = -1;

  @override
  Widget build(BuildContext context) {
    return isListVisible
        ? LocationListExpandedBody(
            isArabic: widget.isArabic,
            data: widget.data,
            onItemClick: (data) {
              if (data.isEmpty) return;
              var selected = widget.data.indexWhere(
                (item) => item.name == data,
              );

              if (selected == -1) return;
              setState(() {
                currentlySelected = selected;
                isListVisible = false;
              });
            },
          )
        : LocationListWrapBody(
            onConfirmClicked: () {
              widget.onValueSelected?.call(currentlySelected);
            },
            onTextBoxClicked: () {
              setState(() {
                isListVisible = true;
              });
            },
            selectedText: currentlySelected == -1 ? "" : widget.data[currentlySelected].name ?? "");
  }
}

class LocationListExpandedBody extends StatefulWidget {
  final List<HospitalsModel> data;
  final Function(String) onItemClick;
  final bool isArabic;

  const LocationListExpandedBody({super.key, required this.data, required this.onItemClick, required this.isArabic});

  @override
  State<LocationListExpandedBody> createState() => _LocationListExpandedBodyState();
}

class _LocationListExpandedBodyState extends State<LocationListExpandedBody> {
  List<HospitalsModel> tempListData = [];
  TextEditingController controller = new TextEditingController();

  @override
  void initState() {
    super.initState();
    setState(() {
      tempListData.addAll(widget.data);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SelectBranchHeader(),
            SizedBox(
              height: 8,
            ),
            TextField(
              controller: controller,
              onChanged: (v) {
                tempListData.clear();
                if (v.length > 0) {
                  for (int i = 0; i < widget.data.length; i++) {
                    if (widget.data[i].name?.toLowerCase().contains(v.toLowerCase()) == true) {
                      tempListData.add(widget.data[i]);
                    }
                  }
                } else {
                  tempListData.addAll(widget.data);
                }
                setState(() {});
              },
              decoration: InputDecoration(
                hintStyle: TextStyle(fontSize: 12),
                hintText: TranslationBase.of(context).searchByBranch,
                suffixIcon: Icon(Icons.search),
                contentPadding: EdgeInsets.symmetric(vertical: 9, horizontal: 14),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8.0),
                  borderSide: BorderSide(
                    color: Colors.grey, // Normal border color
                    width: 1.0,
                  ),
                ),
              ),
            ),
            SizedBox(
              height: 16,
            ),
            ListView.builder(
                itemCount: tempListData.length,
                shrinkWrap: true,
                itemBuilder: (context, index) {
                  return Padding(
                    padding: EdgeInsets.only(bottom: 8),
                    child: SizedBox(
                      height: 24,
                      child: InkWell(
                        onTap: () {
                          widget.onItemClick(tempListData[index].name ?? "");
                        },
                        child: Text(
                          "${widget.isArabic ? tempListData[index].nameN : tempListData[index].name ?? ""}",
                          style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Colors.black, letterSpacing: -0.96),
                        ),
                      ),
                    ),
                  );
                })
          ],
        ),
      ),
    );
  }
}

class LocationListWrapBody extends StatelessWidget {
  final VoidCallback? onConfirmClicked;
  final VoidCallback? onTextBoxClicked;
  final String selectedText;

  const LocationListWrapBody({super.key, this.onConfirmClicked, this.onTextBoxClicked, required this.selectedText});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(24.0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SelectBranchHeader(),
          SizedBox(
            height: 24,
          ),
          ListTile(
            onTap: () {
              onTextBoxClicked?.call();
            },
            title: Text(
              TranslationBase.of(context).selectBranch,
              style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Colors.black, letterSpacing: -0.96),
            ),
            subtitle: selectedText.isEmpty
                ? null
                : Text(
                    selectedText,
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.w400, color: Colors.black, letterSpacing: -0.96),
                  ),
            trailing: Icon(
              Icons.arrow_drop_down_outlined,
              color: Colors.black,
            ),
            shape: RoundedRectangleBorder(
              side: BorderSide(color: Colors.grey, width: 1),
              borderRadius: BorderRadius.circular(8),
            ),
          ),
          SizedBox(
            height: 24,
          ),
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Expanded(
                child: DefaultButton(
                  TranslationBase.of(context).confirm,
                  () {
                    Navigator.pop(context);
                    onConfirmClicked?.call();
                  },
                  color: CustomColors.accentColor,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class SelectBranchHeader extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          TranslationBase.of(context).selectBranch,
          style: TextStyle(fontSize: 24, fontWeight: FontWeight.w600, color: Colors.black, letterSpacing: -0.96),
        ),
        InkWell(
            onTap: () {
              Navigator.of(context).pop();
            },
            child: Padding(
              padding: const EdgeInsets.all(4.0),
              child: Icon(Icons.close),
            ))
      ],
    );
  }
}
