import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:turquessa_mesas_hoster/core/models/sucursal_model.dart';

import '../../mvvm/viewmodels/sucursal_view_model.dart';

class CustomAppbar extends StatefulWidget {
  const CustomAppbar({super.key});

  @override
  State<CustomAppbar> createState() => _CustomAppbarState();
}

class _CustomAppbarState extends State<CustomAppbar> {
  @override
  void initState() {
    super.initState();
    final _sucursalViewModel =
        Provider.of<SucursalViewModel>(context, listen: false);
    _sucursalViewModel.fetchLocalSucursales();

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      Provider.of<SucursalViewModel>(context, listen: false)
          .sincronizarSucursalesDesdeApi();

      await _sucursalViewModel.sincronizarSucursales();
      await _sucursalViewModel.fetchLocalSucursales();
    });
  }

  String? _selectedValue;

  @override
  Widget build(BuildContext context) {
    final sucursalViewModel = Provider.of<SucursalViewModel>(context);
    final sucursales = sucursalViewModel.sucursales;
    return Row(
      children: [
        Image.asset(
          'assets/Turquessa.png',
          height: 100,
        ),
        const SizedBox(width: 10),
        SizedBox(
          width: 240,
          child: Expanded(
            child: DropdownButtonFormField<String>(
              value: _selectedValue,
              hint: Text(
                _selectedValue?.isEmpty ?? true
                    ? 'Selecciona una sucursal'
                    : '',
                style:
                    TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
              ),
              icon: const Icon(Icons.arrow_drop_down),
              decoration: InputDecoration(
                contentPadding:
                    const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(15),
                  borderSide: BorderSide.none,
                ),
                filled: true,
                fillColor: Colors.white,
              ),
              items: sucursales
                  .map((e) => DropdownMenuItem(
                        value: e.nombre,
                        child: Text(e.nombre ?? ""),
                      ))
                  .toList(),
              onChanged: (value) {
                setState(() {
                  _selectedValue = value;
                  // setSelectedSucursal(value as Sucursal);
                });
              },
            ),
          ),
        )
      ],
    );
  }
}
