import 'dart:io';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_export.dart';
import 'package:hmg_patient_app_new/core/utils/validation_utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/create_e_referral_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/e_referral/e_referral_form_manager.dart';
import 'package:provider/provider.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/features/habib_wallet/habib_wallet_view_model.dart';
import 'package:hmg_patient_app_new/widgets/dropdown/dropdown_widget.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/image_picker.dart';


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

  @override
  State<OtherDetailsStep> createState() => _OtherDetailsStepState();
}

class _OtherDetailsStepState extends State<OtherDetailsStep> {
  final TextEditingController _medicalReportController = TextEditingController();
  final TextEditingController _insuranceController = TextEditingController();

  late ReferralFormManager _formManager;

  @override
  void initState() {
    super.initState();
    _formManager = context.read<ReferralFormManager>();
    _updateMedicalReportText();
    _updateInsuranceText();
  }

  @override
  void didUpdateWidget(OtherDetailsStep oldWidget) {
    super.didUpdateWidget(oldWidget);
    _updateMedicalReportText();
    _updateInsuranceText();
  }

  void _updateMedicalReportText() {
    final hasMedicalReports = _formManager.formData.medicalReportImages.isNotEmpty;
    _medicalReportController.text = hasMedicalReports
        ? '${_formManager.formData.medicalReportImages.length} file(s) selected'
        : '';
  }

  void _updateInsuranceText() {
    final hasInsuranceDocs = _formManager.formData.insuredPatientImages.isNotEmpty;
    _insuranceController.text = hasInsuranceDocs
        ? '${_formManager.formData.insuredPatientImages.length} file(s) selected'
        : '';

  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ReferralFormManager>(
      builder: (context, formManager, child) {
        return Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          child: ListView(
            padding: EdgeInsets.zero,
            physics: const BouncingScrollPhysics(),
            children: [
              const SizedBox(height: 12),
              _buildSectionTitle(LocaleKeys.otherDetails.tr(context: context)),
              const SizedBox(height: 12),
              _buildMedicalReportField(formManager),
              _buildBranchField(context, formManager),
              _buildInsuranceCheckbox(formManager),
              if (formManager.formData.isPatientInsured) _buildInsuranceField(formManager),
            ],
          ),
        );
      },
    );
  }

  Widget _buildSectionTitle(String title) {
    return Text(
        title,
        style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 16)
    ).paddingSymmetrical(4, 0);
  }

  Widget _buildMedicalReportField(ReferralFormManager formManager) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InkWell(
          child: TextInputWidget(
            controller: _medicalReportController,
            padding: EdgeInsets.symmetric(
              vertical: ResponsiveExtension(12).h,
              horizontal: ResponsiveExtension(16).h,
            ),
            hintText: LocaleKeys.medicalReport.tr(context: context),
            labelText: LocaleKeys.selectAttachment.tr(context: context),
            suffix: const Icon(Icons.attachment),
            isReadOnly: true,
            errorMessage: formManager.errors.medicalReport,
            hasError:  !ValidationUtils.isNullOrEmpty(formManager.errors.medicalReport),
          ),
          onTap: () {
            ImageOptions.showImageOptionsNew(
              context,
              false,
                  (String image, File file) {
                _addMedicalReport(image, file, formManager);
              },
            );
          },
        ),
        if (formManager.formData.medicalReportImages.isNotEmpty)
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
            child: Wrap(
              spacing: 8.0,
              children: formManager.formData.medicalReportImages.asMap().entries.map((entry) {
                final index = entry.key;
                return Chip(
                  label: Text(LocaleKeys.medicalReportNumber.tr(context: context, namedArgs: {'number': '${index + 1}'})),
                  deleteIcon: const Icon(Icons.close, size: 16),
                  onDeleted: () {
                    _removeMedicalReport(index, formManager);
                  },
                );
              }).toList(),
            ),
          ),
      ],
    ).paddingSymmetrical(0, 4);
  }

  Widget _buildBranchField(BuildContext context, ReferralFormManager formManager) {
    return DropdownWidget(
      labelText: LocaleKeys.branch.tr(),
      hintText: formManager.formData.branch?.desciption ?? LocaleKeys.selectBranch.tr(),
      isEnable: false,
      hasSelectionCustomIcon: true,
      labelColor: Colors.black,
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
      selectionCustomIcon: AppAssets.arrow_down,
      leadingIcon: AppAssets.hospital,
      dropdownItems: [],
      errorMessage: formManager.errors.branch,
      hasError:  !ValidationUtils.isNullOrEmpty(formManager.errors.branch),
    ).paddingSymmetrical(0, 4).onPress(() {
      _showBranchBottomSheet(context, formManager);
    });
  }

  Widget _buildInsuranceCheckbox(ReferralFormManager formManager) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Row(
          children: [
            Checkbox(
              value: formManager.formData.isPatientInsured,
              activeColor: Colors.red,
              onChanged: (bool? newValue) {
                final value = newValue ?? false;
                formManager.updateIsPatientInsured(value);
                if (!value) {
                  _updateInsuranceText();
                }
                setState(() {});
              },
            ),
             Padding(
              padding: EdgeInsets.all(5.0),
              child:
                LocaleKeys.patientIsInsured.tr(context: context).toText14(
                  color: Colors.black,
                  weight: FontWeight.w600,
                ),
               // style: TextStyle(fontSize: 14, isBold: true),
              //),
            ),
          ],
        ),
      ],
    ).paddingSymmetrical(0, 4);
  }

  Widget _buildInsuranceField(ReferralFormManager formManager) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InkWell(
          child: TextInputWidget(
            controller: _insuranceController,
            padding: EdgeInsets.symmetric(
              vertical: ResponsiveExtension(12).h,
              horizontal: ResponsiveExtension(16).h,
            ),
            hintText: LocaleKeys.insuranceDocument.tr(context: context),
            labelText: LocaleKeys.selectAttachment.tr(context: context),
            suffix: const Icon(Icons.attachment),
            isReadOnly: true,
            errorMessage: formManager.errors.insuredDocument,
            hasError:  !ValidationUtils.isNullOrEmpty(formManager.errors.insuredDocument),
          ),
          onTap: () {
            ImageOptions.showImageOptionsNew(
              context,
              false,
                  (String image, File file) {
                _addInsuranceDocument(image, file, formManager);
              },
            );
          },
        ),
        if (formManager.formData.insuredPatientImages.isNotEmpty)
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
            child: Wrap(
              spacing: 8.0,
              children: formManager.formData.insuredPatientImages.asMap().entries.map((entry) {
                final index = entry.key;
                return Chip(
                  label: Text('Insurance ${index + 1}'),
                  deleteIcon: const Icon(Icons.close, size: 16),
                  onDeleted: () {
                    _removeInsuranceDocument(index, formManager);
                  },
                );
              }).toList(),
            ),
          ),
      ],
    );
  }

  void _showBranchBottomSheet(BuildContext context, ReferralFormManager formManager) {
    showCommonBottomSheetWithoutHeight(
      context,
      title: LocaleKeys.selectBranch.tr(context: context),
      child: Consumer<HabibWalletViewModel>(
        builder: (context, habibWalletVM, child) {
          final hospitals = habibWalletVM.advancePaymentHospitals;
          if (hospitals.isEmpty) {
            return const Center(
              child: Padding(
                padding: EdgeInsets.all(16.0),
                child: Text('No branches available'),
              ),
            );
          }

          return DecoratedBox(
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: Colors.white,
                customBorder:  BorderRadius.all(Radius.circular(24.h)) ,

              ), child: ListView.builder(
            shrinkWrap: true,
            padding: EdgeInsets.all(16.h),
            physics: const BouncingScrollPhysics(),
            itemBuilder: (context, index) {
              final branch = hospitals[index];
              return ListTile(
                title: (branch.desciption ?? 'Unknown').toText14(),
                onTap: () {
                  formManager.updateBranch(branch);
                  Navigator.pop(context);
                      setState(() {});
                    },
                  );
            },
           // separatorBuilder: (context, index) => const Divider(),
            itemCount: hospitals.length,
          ));
        },
      ),
      useSafeArea: true,
      isFullScreen: false,
      isCloseButtonVisible: true,
    );
  }

  void _addMedicalReport(String image, File file, ReferralFormManager formManager) {
    // Remove max 1 file check
    // Max 1 MB
    final fileSizeInBytes = file.lengthSync();
    if (fileSizeInBytes > 1 * 1024 * 1024) {
      formManager.setFieldError('medicalReport', 'File size exceeds 1MB limit.');
      return;
    }
    final newAttachment = EReferralAttachment(
        fileName: 'medical_report_formManager.formData.medicalReportImages.length + 1}.png',
        base64String: image
    );

    formManager.addMedicalReport(newAttachment);
    _updateMedicalReportText();
  }

  void _removeMedicalReport(int index, ReferralFormManager formManager) {
    formManager.removeMedicalReport(index);
    _updateMedicalReportText();
  }

  void _addInsuranceDocument(String image, File file, ReferralFormManager formManager) {
    // Remove max 1 file check
    // Max 1 MB
    final fileSizeInBytes = file.lengthSync();
    if (fileSizeInBytes > 1 * 1024 * 1024) {
      formManager.setFieldError('insuredDocument', 'File size exceeds 1MB limit.');
      return;
    }
    final newAttachment = EReferralAttachment(
        fileName: 'insurance_formManager.formData.insuredPatientImages.length + 1}.png',
        base64String: image
    );

    formManager.addInsuranceDocument(newAttachment);
    _updateInsuranceText();
  }

  void _removeInsuranceDocument(int index, ReferralFormManager formManager) {
    formManager.removeInsuranceDocument(index);
    _updateInsuranceText();
  }

  @override
  void dispose() {
    _medicalReportController.dispose();
    _insuranceController.dispose();
    super.dispose();
  }
}