import 'package:flutter/material.dart';

import '../../../models/lookup.dart';
import '../../app_style/colors.dart';
import '../../app_style/sizing.dart';

class SingleStatusMenu extends StatefulWidget {
  final List<Lookup>? statuses;
  final Lookup? initialStatus;
  final Function(Lookup?)? onSelect;

  const SingleStatusMenu({
    Key? key,
    this.onSelect,
    this.statuses,
    this.initialStatus,
  }) : super(key: key);

  @override
  SingleStatusMenuState createState() => SingleStatusMenuState();
}

class SingleStatusMenuState extends State<SingleStatusMenu> {
  Lookup? _selectedStatus;

  @override
  void didUpdateWidget(covariant SingleStatusMenu oldWidget) {
    if (widget.initialStatus != null) {
      _selectedStatus = widget.initialStatus?.id != null
          ? widget.statuses?.firstWhere((element) {
              return element.id == widget.initialStatus?.id;
            })
          : null;
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void initState() {
    if (widget.initialStatus != null) {
      _selectedStatus = widget.initialStatus?.id != null
          ? widget.statuses?.firstWhere((element) {
              return element.id == widget.initialStatus?.id;
            })
          : null;
    }

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(
        color: AColors.inputFieldBackgroundColor,
        border: Border.all(
          color: const Color(0xffefefef),
        ),
        borderRadius: BorderRadius.circular(
          AppStyle.borderRadius * AppStyle.getScaleFactor(context),
        ),
        // boxShadow: const [
        //   AppStyle.boxShadow
        // ]
      ),
      child: DropdownButton<Lookup>(
        value: _selectedStatus,
        iconSize: 24,
        icon: const Icon(Icons.keyboard_arrow_down_rounded),
        elevation: 0,
        isExpanded: true,
        hint: Text(
          "Select",
          style: Theme.of(context).textTheme.subtitle1,
        ),
        style: TextStyle(color: Theme.of(context).primaryColor),
        underline: const SizedBox.shrink(),
        onChanged: (Lookup? newValue) {
          setState(() {
            _selectedStatus = newValue;
          });
          if (widget.onSelect != null) {
            widget.onSelect!(newValue);
          }
        },
        items: widget.statuses?.map<DropdownMenuItem<Lookup>>((Lookup value) {
          return DropdownMenuItem<Lookup>(
            value: value,
            child: Text(
              value.label ?? '',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(color: Theme.of(context).primaryColor, fontWeight: FontWeight.w600),
            ),
          );
        }).toList(),
      ),
    );
  }
}
