import 'dart:io';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/config/routes.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/models/etqan_ovr/etqan_getprojects_model.dart';
import 'package:mohem_flutter_app/provider/etqan_ovr_provider.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:mohem_flutter_app/widgets/bottom_sheet.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';
import 'package:mohem_flutter_app/widgets/image_picker.dart';
import 'package:provider/provider.dart';

class EtqanOvrCreateRequest extends StatefulWidget {
  const EtqanOvrCreateRequest({Key? key}) : super(key: key);

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

class _EtqanOvrCreateRequestState extends State<EtqanOvrCreateRequest> {
  final TextEditingController _descriptionController = TextEditingController();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      var provider = context.read<EtqanOvrProviderModel>();
      provider.initSpeech();
      provider.fetchEtqanProjects(context);
      provider.clearCreateRequestForm();
    });
  }

  @override
  void dispose() {
    // Stop listening if active
    context.read<EtqanOvrProviderModel>().stopListening();
    _descriptionController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(context, title: LocaleKeys.reportIncident.tr(), showHomeButton: false),
      body: Consumer<EtqanOvrProviderModel>(
        builder: (BuildContext context, EtqanOvrProviderModel provider, Widget? child) {
          return Column(
            children: <Widget>[
              (ListView(
                shrinkWrap: true,
                physics: const BouncingScrollPhysics(),
                padding: const EdgeInsets.all(21),
                children: <Widget>[
                  _buildDropdownField(
                    label: LocaleKeys.project.tr(),
                    hint: LocaleKeys.selectProject.tr(),
                    value: _getProjectDisplayName(provider.selectedProject),
                    onTap: () => _showProjectSelectionSheet(context, provider),
                    isMandatory: true,
                  ),
                  16.height,
                  // _buildDropdownField(
                  //   label: 'Employee Number',
                  //   hint: 'Write a message',
                  //   value: provider.selectedEmployeeNumber,
                  //   onTap: () {
                  //     // TODO: Show employee selection dialog
                  //   },
                  // ),
                  // 16.height,
                  _buildAttachmentSection(provider),
                  16.height,
                  _buildDescriptionField(provider),
                  8.height,
                  _buildAnonymousCheckbox(provider),
                  24.height,
                ],
              )).expanded,
              DefaultButton(LocaleKeys.submit.tr(), () async {
                provider.setDescription(_descriptionController.text);
                if (provider.selectedProject == null) {
                  Utils.showErrorDialog(
                    context: context,
                    message: LocaleKeys.pleaseSelectProject.tr(),
                    onOkTapped: () {
                      Navigator.of(context).pop();
                    },
                  );
                  return;
                }
                if (!provider.isDescriptionValid()) {
                  Utils.showErrorDialog(
                    context: context,
                    message: LocaleKeys.pleaseEnterDescription.tr(),
                    onOkTapped: () {
                      Navigator.of(context).pop();
                    },
                  );
                  return;
                }
                Map<String, dynamic>? ticketInfo = await provider.submitRequest(context);
                if (ticketInfo != null) {
                  String ticketNumber = ticketInfo['ticketNumber'] ?? '';
                  String ticketId = ticketInfo['id'] ?? '';
                  // String successMessage = '${LocaleKeys.requestCreatedSuccessfully.tr()}\n\n${LocaleKeys.ticketNumber.tr()}: $ticketNumber\n${LocaleKeys.ticketId.tr()}: $ticketId';
                  String successMessage = '${LocaleKeys.requestCreatedSuccessfully.tr()}\n\n${LocaleKeys.ticketNumber.tr()}: $ticketNumber';
                  Utils.showErrorDialog(
                    context: context,
                    message: successMessage,
                    onOkTapped: () {
                      Navigator.pop(context);
                      Navigator.pop(context);
                      // Navigator.popAndPushNamed(context, AppRoutes.etqanOvr);
                    },
                    onCloseTap: () {
                      Navigator.pop(context);
                      Navigator.pop(context);
                      // Navigator.popAndPushNamed(context, AppRoutes.etqanOvr);
                    },
                  );
                }
              }).insideContainer,
            ],
          );
        },
      ),
    );
  }

  String? _getProjectDisplayName(EtqanGetProjectsResponse? project) {
    if (project == null) return null;
    return AppState().isArabic(context) ? project.projectAr : project.projectEn;
  }

  void _showProjectSelectionSheet(BuildContext context, EtqanOvrProviderModel provider) {
    if (provider.getEtqanProjectsList == null || provider.getEtqanProjectsList!.isEmpty) {
      return;
    }
    showMyBottomSheet(
      context,
      callBackFunc: () {},
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: Text(LocaleKeys.selectProject.tr(), style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Color(0xff2B353E))),
          ),
          const Divider(),
          ListView.separated(
            shrinkWrap: true,
            physics: const BouncingScrollPhysics(),
            itemCount: provider.getEtqanProjectsList!.length,
            separatorBuilder: (BuildContext context, int index) => const Divider(height: 1),
            itemBuilder: (BuildContext context, int index) {
              EtqanGetProjectsResponse project = provider.getEtqanProjectsList![index];
              bool isSelected = provider.selectedProject?.projectId == project.projectId;
              return ListTile(
                title: Text(
                  AppState().isArabic(context) ? (project.projectAr ?? '') : (project.projectEn ?? ''),
                  style: TextStyle(fontSize: 14, fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400, color: isSelected ? MyColors.gradiantEndColor : const Color(0xff2B353E)),
                ),
                trailing: isSelected ? const Icon(Icons.check, color: MyColors.gradiantEndColor) : null,
                onTap: () {
                  provider.setSelectedProject(project);
                  Navigator.pop(context);
                },
              );
            },
          ),
          16.height,
        ],
      ),
    );
  }

  Widget _buildDropdownField({required String label, required String hint, String? value, required VoidCallback onTap, bool isMandatory = false}) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(15),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 15),
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(15), color: Colors.white, border: Border.all(color: const Color(0xffefefef), width: 1)),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Text(label, style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.44)),
                      if (isMandatory) const Text(' *', style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: Colors.red, letterSpacing: -0.44)),
                    ],
                  ),
                  const SizedBox(height: 4),
                  Text(value ?? hint, style: TextStyle(fontSize: 14, fontWeight: FontWeight.w400, color: value != null ? const Color(0xff2B353E) : const Color(0xff575757), letterSpacing: -0.56)),
                ],
              ),
            ),
            const Icon(Icons.keyboard_arrow_down, color: Color(0xff575757)),
          ],
        ),
      ),
    );
  }

  Widget _buildAttachmentSection(EtqanOvrProviderModel provider) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(15), color: Colors.white, border: Border.all(color: const Color(0xffefefef), width: 1)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(LocaleKeys.supportingDocument.tr(), style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xff2B353E))),
          const SizedBox(height: 12),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(LocaleKeys.attachments.tr(), style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: Color(0xff2B353E))),
              if (provider.attachment == null)
                InkWell(
                  onTap: () {
                    ImageOptions.showImageOptionsNew(context, true, (String base64, File file) {
                      provider.setAttachment(file, base64);
                      Navigator.of(context).pop();
                    });
                  },
                  borderRadius: BorderRadius.circular(8),
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
                    decoration: BoxDecoration(color: MyColors.gradiantEndColor, borderRadius: BorderRadius.circular(8)),
                    child: Text(LocaleKeys.add.tr(), style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Colors.white)),
                  ),
                ),
            ],
          ),
          if (provider.attachment != null) ...<Widget>[
            const SizedBox(height: 12),
            Padding(
              padding: const EdgeInsets.only(bottom: 8),
              child: Row(
                children: <Widget>[
                  const Icon(Icons.attach_file, size: 18, color: Color(0xff575757)),
                  const SizedBox(width: 8),
                  Expanded(child: Text(provider.attachment!.path.split('/').last, style: const TextStyle(fontSize: 12, color: Color(0xff575757)), overflow: TextOverflow.ellipsis)),
                  InkWell(
                    onTap: () {
                      provider.removeAttachment();
                    },
                    child: const Icon(Icons.close, size: 18, color: Colors.red),
                  ),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildDescriptionField(EtqanOvrProviderModel provider) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 15),
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(15), color: Colors.white, border: Border.all(color: const Color(0xffefefef), width: 1)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                children: <Widget>[
                  Text(LocaleKeys.description.tr(), style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.44)),
                  const Text(' *', style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: Colors.red, letterSpacing: -0.44)),
                ],
              ),
              GestureDetector(
                onTap:
                    provider.speechEnabled
                        ? () {
                          String localeId = AppState().isArabic(context) ? 'ar_SA' : 'en_US';
                          provider.toggleListening(localeId, _descriptionController);
                        }
                        : null,
                child: Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(color: provider.isListening ? MyColors.gradiantEndColor.withOpacity(0.1) : Colors.transparent, borderRadius: BorderRadius.circular(20)),
                  child: Icon(
                    provider.isListening ? Icons.mic : Icons.mic_none,
                    color: provider.isListening ? MyColors.gradiantEndColor : (provider.speechEnabled ? MyColors.grey57Color : Colors.grey.shade300),
                    size: 24,
                  ),
                ),
              ),
            ],
          ),
          if (provider.isListening)
            Padding(
              padding: const EdgeInsets.only(bottom: 8),
              child: Row(
                children: <Widget>[
                  Container(width: 8, height: 8, decoration: BoxDecoration(color: Colors.red, borderRadius: BorderRadius.circular(4))),
                  const SizedBox(width: 8),
                  const Text('Listening...', style: TextStyle(fontSize: 12, color: MyColors.gradiantEndColor, fontWeight: FontWeight.w500)),
                ],
              ),
            ),
          TextField(
            controller: _descriptionController,
            maxLines: 4,
            onChanged: (String value) => provider.setDescription(value),
            style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w400, color: Color(0xff2B353E), letterSpacing: -0.44),
            decoration: InputDecoration(
              isDense: true,
              hintText: LocaleKeys.writeAMessage.tr(),
              hintStyle: const TextStyle(fontSize: 14, fontWeight: FontWeight.w400, color: Color(0xff575757), letterSpacing: -0.56),
              contentPadding: EdgeInsets.zero,
              border: InputBorder.none,
              focusedBorder: InputBorder.none,
              enabledBorder: InputBorder.none,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAnonymousCheckbox(EtqanOvrProviderModel provider) {
    return InkWell(
      onTap: () {
        provider.setIsAnonymous(!provider.isAnonymous);
      },
      child: Row(
        children: <Widget>[
          Checkbox(
            value: provider.isAnonymous,
            onChanged: (bool? value) {
              if (value != null) {
                provider.setIsAnonymous(value);
              }
            },
            activeColor: MyColors.gradiantEndColor,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
          ),

          Expanded(child: Text(LocaleKeys.submitAsAnonymous.tr(), style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: Color(0xff2B353E), letterSpacing: -0.44))),
        ],
      ),
    );
  }
}
