import 'package:flutter/material.dart';

import '../../../controllers/localization/localization.dart';
import '../../../models/lookup.dart';
import '../../../models/subtitle.dart';
import '../../../models/visits/visits_search.dart';
import '../../app_style/sizing.dart';
import '../app_text_form_field.dart';
import '../buttons/app_button.dart';
import '../buttons/app_small_button.dart';
import '../date_and_time/from_to_date_bar.dart';
import '../hospitals/hospital_auto_complete_field.dart';
import '../titles/app_sub_title.dart';
import 'filter_item.dart';

class VisitsSearchDialog extends StatefulWidget {
  final VisitsSearch initialSearchValue;
  final bool? expandedSearch;
  final Function(VisitsSearch) onSearch;

  const VisitsSearchDialog({
    Key? key,
    required this.initialSearchValue,
    this.expandedSearch,
    required this.onSearch,
  }) : super(key: key);

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

class VisitsSearchDialogState extends State<VisitsSearchDialog> with TickerProviderStateMixin {
  VisitsSearch? _search;
  List<Lookup> status = const [
    Lookup(
      label: "Done",
      id: 0,
    ),
    Lookup(label: "Not Yet", id: 1),
    Lookup(
      label: "On Hold",
      id: 2,
    ),
  ];

  List<Lookup> contactStatus = const [
    Lookup(
      label: "Hospital Employee",
      key: "H",
    ),
    Lookup(label: "Under Warranty", key: "CW"),
    Lookup(
      label: "Under Maintenance Contract",
      key: "CC",
    ),
  ];

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    _search = VisitsSearch();
    _search?.fromSearch(widget.initialSearchValue);
  }

  @override
  Widget build(BuildContext context) {
    Subtitle? subtitle = AppLocalization.of(context)?.subtitle;
    DateTime today = DateTime.now();
    return SizedBox(
      height: MediaQuery.of(context).size.height / 1.3,
      child: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                ASmallButton(
                  text: subtitle?.cancel,
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
                ASmallButton(
                  text: subtitle?.search,
                  onPressed: () {
                    if (!(_formKey.currentState?.validate() ?? true)) {
                      return;
                    }
                    _formKey.currentState?.save();
                    Navigator.of(context).pop(_search);
                  },
                )
              ],
            ),
            ATextFormField(
              initialValue: _search?.deviceSerialNumber,
              hintText: subtitle?.serialNumber,
              style: Theme.of(context).textTheme.titleLarge,
              textInputAction: TextInputAction.search,
              onAction: () {
                if (!(_formKey.currentState?.validate() ?? true)) return;
                _formKey.currentState?.save();
                Navigator.of(context).pop(_search);
              },
              onSaved: (value) {
                _search?.deviceSerialNumber = value ?? '';
              },
            ),
            SizedBox(height: 8.0 * AppStyle.getScaleFactor(context)),
            HospitalAutoCompleteField(
              initialValue: _search?.hospitalName ?? '',
              onSave: (value) {
                _search?.hospitalName = value;
              },
              onSearch: (value) {
                _search?.hospitalName = value;
                Navigator.of(context).pop(_search);
              },
            ),
            SizedBox(
              height: 8.0 * AppStyle.getScaleFactor(context),
            ),
            ATextFormField(
              initialValue: _search?.brand,
              hintText: subtitle?.brand,
              style: Theme.of(context).textTheme.titleLarge,
              textInputAction: TextInputAction.search,
              onAction: () {
                if (!(_formKey.currentState?.validate() ?? false)) return;
                _formKey.currentState?.save();
                Navigator.of(context).pop(_search);
              },
              onSaved: (value) {
                _search?.brand = value ?? '';
              },
            ),
            SizedBox(
              height: 8.0 * AppStyle.getScaleFactor(context),
            ),
            ATextFormField(
              initialValue: _search?.model,
              hintText: subtitle?.model,
              style: Theme.of(context).textTheme.titleLarge,
              textInputAction: TextInputAction.search,
              onAction: () {
                if (!(_formKey.currentState?.validate() ?? true)) return;
                _formKey.currentState?.save();
                Navigator.of(context).pop(_search);
              },
              onSaved: (value) {
                _search?.model = value ?? '';
              },
            ),
            SizedBox(
              height: 8.0 * AppStyle.getScaleFactor(context),
            ),
            ASubTitle(subtitle?.status ?? ''),
            SizedBox(
              height: 4.0 * AppStyle.getScaleFactor(context),
            ),
            Wrap(
              spacing: 10,
              runSpacing: 10,
              children: List.generate(status.length, (index) {
                bool isSelected = _search?.statusValue == status[index].id;
                return FilterItem(
                  isSelected: isSelected,
                  onSelected: () {
                    if (isSelected) {
                      _search?.statusValue = null;
                    } else {
                      _search?.statusValue = status[index].id;
                    }
                    setState(() {});
                  },
                  status: status[index],
                );
              }),
            ),
            SizedBox(
              height: 8.0 * AppStyle.getScaleFactor(context),
            ),
            ASubTitle(subtitle?.contactStatus ?? ''),
            SizedBox(
              height: 4.0 * AppStyle.getScaleFactor(context),
            ),
            Wrap(
              spacing: 10,
              runSpacing: 10,
              children: List.generate(
                contactStatus.length,
                (index) {
                  bool isSelected = _search?.contactStatus == contactStatus[index].key;
                  return FilterItem(
                    isSelected: isSelected,
                    onSelected: () {
                      if (isSelected) {
                        _search?.contactStatus = null;
                      } else {
                        _search?.contactStatus = contactStatus[index].key;
                      }
                      setState(() {});
                    },
                    status: contactStatus[index],
                  );
                },
              ),
            ),
            SizedBox(
              height: 8.0 * AppStyle.getScaleFactor(context),
            ),
            ASubTitle(subtitle?.actualDate ?? ''),
            SizedBox(
              height: 4.0 * AppStyle.getScaleFactor(context),
            ),
            FromToDateBar(
              from: _search?.actualDateFrom,
              to: _search?.actualDateTo,
              onPickFrom: (date) {
                _search?.actualDateFrom = date;
              },
              onPickTo: (date) {
                _search?.actualDateTo = date;
              },
            ),
            SizedBox(
              height: 8.0 * AppStyle.getScaleFactor(context),
            ),
            ASubTitle(subtitle?.expectDate ?? ''),
            SizedBox(
              height: 4.0 * AppStyle.getScaleFactor(context),
            ),
            FromToDateBar(
              from: _search?.expectedDateFrom ?? DateTime(today.year, today.month, 1),
              to: _search?.expectedDateTo ?? DateTime(today.year, (today.month + 1).clamp(1, 12), today.month == 12 ? 31 : 0),
              onPickFrom: (date) {
                _search?.expectedDateFrom = date;
              },
              onPickTo: (date) {
                _search?.expectedDateTo = date;
              },
            ),
            Visibility(
              visible: _search?.toSearchString().isNotEmpty ?? false,
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                child: AButton(
                  padding: EdgeInsets.zero,
                  text: subtitle?.clearSearch ?? '',
                  onPressed: () {
                    _search = VisitsSearch();
                    Navigator.of(context).pop(_search);
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
