import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/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/smartwatch_health_data/health_provider.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/smartwatches/widgets/health_metric.dart';
import 'package:hmg_patient_app_new/presentation/smartwatches/widgets/health_metric_card.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/custom_tab_bar.dart';
import 'package:provider/provider.dart';
import 'package:health/health.dart';

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

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

class _HealthDashboardState extends State<HealthDashboard> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final dateFormat = DateFormat('MMM dd, yyyy', "en-US");
  final timeFormat = DateFormat('hh:mm a', "en-US");

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    Future.microtask(
      () async {
        await Health().configure();
        context.read<HealthProvider>().fetchHealthData();
      },
    );
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Consumer<HealthProvider>(
        builder: (context, healthProvider, child) {
          return SingleChildScrollView(
            child: Column(
              children: [
                SizedBox(height: 96.h),
                CustomTabBar(
                  activeTextColor: Color(0xffED1C2B),
                  activeBackgroundColor: Color(0xffED1C2B).withValues(alpha: .1),
                  tabs: [
                    CustomTabBarModel(null, "Overview".needTranslation),
                    CustomTabBarModel(null, "Details".needTranslation),
                  ],
                  onTabChange: (index) {
                    healthProvider.onTabChanged(index);
                  },
                ).paddingSymmetrical(24.h, 0.h),
                SizedBox(height: 24.h),
                getSelectedTabData(healthProvider.selectedTabIndex, healthProvider).paddingSymmetrical(24.w, 0),
              ],
            ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => context.read<HealthProvider>().fetchHealthData(),
        tooltip: 'Refresh health data',
        child: Icon(Icons.refresh),
      ),
    );
  }

  Widget getSelectedTabData(int index, HealthProvider healthProvider) {
    switch (index) {
      case 0:
        return _buildOverviewTab(healthProvider);
      case 1:
        return _buildDetailsTab(healthProvider);
      default:
        SizedBox.shrink();
    }
    return Container();
  }

  Widget _buildOverviewTab(HealthProvider healthProvider) {
    if (healthProvider.isLoading) {
      return _buildLoadingState();
    }

    if (healthProvider.error != null) {
      return _buildErrorState(healthProvider.error!);
    }
    return CustomScrollView(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      slivers: [
        SliverToBoxAdapter(
          child: _buildTimeRangeSelector(healthProvider),
        ),
        SliverPadding(
          padding: EdgeInsets.symmetric(vertical: 12.w),
          sliver: SliverGrid(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 16,
              crossAxisSpacing: 16,
              childAspectRatio: 0.62,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                final metric = HealthMetrics.metrics[index];
                return HealthMetricCard(
                  metric: metric,
                  data: healthProvider.healthData[metric.type] ?? [],
                  onTap: () => _showMetricDetails(context, metric, healthProvider),
                );
              },
              childCount: HealthMetrics.metrics.length,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildDetailsTab(HealthProvider healthProvider) {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: HealthMetrics.metrics.length,
      shrinkWrap: true,
      itemBuilder: (context, index) {
        final metric = HealthMetrics.metrics[index];
        final data = healthProvider.healthData[metric.type] ?? [];

        return Card(
          color: AppColors.whiteColor,
          margin: EdgeInsets.only(bottom: 16),
          child: ExpansionTile(
            leading: Icon(
              metric.icon,
              color: metric.color,
              size: 32.h,
            ),
            // title: Text(metric.name),
            title: (getIt.get<AppState>().isArabic() ? metric.nameAr : metric.nameEn).toText14(isBold: true),
            subtitle: Text(
              data.isEmpty ? LocaleKeys.noDataAvailable.tr(context: context) : '${_getValueAsDouble(data.last.value, metric.type).toStringAsFixed(1)} ${metric.unit}',
            ),
            children: [
              Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    metric.description.toText13(),
                    SizedBox(height: 16.h),
                    if (data.isNotEmpty) ...[
                      Text(
                        'History',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                      ),
                      SizedBox(height: 8),
                      ...data.reversed
                          .take(5)
                          .map((point) => Padding(
                                padding: const EdgeInsets.only(bottom: 8),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      dateFormat.format(point.dateFrom),
                                      style: TextStyle(color: Colors.grey[600]),
                                    ),
                                    Text(
                                      '${_getValueAsDouble(point.value, metric.type).toStringAsFixed(1)} ${metric.unit}',
                                      style: TextStyle(fontWeight: FontWeight.bold),
                                    ),
                                  ],
                                ),
                              ))
                          .toList(),
                    ],
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildTimeRangeSelector(HealthProvider provider) {
    return Container(
      height: 40,
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: [
          for (final range in ['1D', '7D', '1M', '3M', '1Y'])
            Padding(
              padding: const EdgeInsets.only(right: 8),
              child: ChoiceChip(
                label: Text(range),
                labelStyle: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
                checkmarkColor: AppColors.primaryRedColor,
                selected: provider.selectedTimeRange == range,
                selectedColor: AppColors.secondaryLightRedColor,
                onSelected: (selected) {
                  if (selected) {
                    provider.updateTimeRange(range);
                  }
                },
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildLoadingState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(),
          SizedBox(height: 16),
          Text('Loading health data...'),
        ],
      ),
    );
  }

  Widget _buildErrorState(String error) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 48,
            color: Colors.red,
          ),
          SizedBox(height: 16),
          Text(
            'Error loading health data',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 8),
          Text(
            error,
            textAlign: TextAlign.center,
            style: TextStyle(color: Colors.grey[600]),
          ),
          SizedBox(height: 24),
          ElevatedButton(
            onPressed: () => context.read<HealthProvider>().fetchHealthData(),
            child: Text('Try Again'),
          ),
        ],
      ),
    );
  }

  void _showMetricDetails(
    BuildContext context,
    HealthMetricInfo metric,
    HealthProvider provider,
  ) {
    final data = provider.healthData[metric.type] ?? [];

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) => DraggableScrollableSheet(
        initialChildSize: 0.7,
        minChildSize: 0.5,
        maxChildSize: 0.95,
        expand: false,
        builder: (context, scrollController) => Container(
          padding: EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Center(
                child: Container(
                  width: 40,
                  height: 4,
                  margin: EdgeInsets.only(bottom: 16),
                  decoration: BoxDecoration(
                    color: Colors.grey[300],
                    borderRadius: BorderRadius.circular(2),
                  ),
                ),
              ),
              Row(
                children: [
                  Icon(metric.icon, color: metric.color, size: 30),
                  SizedBox(width: 16),
                  (getIt.get<AppState>().isArabic() ? metric.nameAr : metric.nameEn).toText24(isBold: true),
                  // Text(
                  //   metric.name,
                  //   style: TextStyle(
                  //     fontSize: 24,
                  //     fontWeight: FontWeight.bold,
                  //   ),
                  // ),
                ],
              ),
              SizedBox(height: 16),
              Text(
                metric.description,
                style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 16,
                ),
              ),
              SizedBox(height: 24),
              Text(
                'Healthy Range',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(height: 8),
              '${metric.minHealthyValue} - ${metric.maxHealthyValue} ${metric.unit}'.toText16(isBold: true, color: AppColors.primaryRedColor),
              // Text(
              //   '${metric.minHealthyValue} - ${metric.maxHealthyValue} ${metric.unit}',
              //   style: TextStyle(
              //     color: mainPurple,
              //     fontSize: 16,
              //   ),
              // ),
              SizedBox(height: 24),
              if (data.isNotEmpty) ...[
                Text(
                  'History',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(height: 16),
                Expanded(
                  child: ListView.builder(
                    controller: scrollController,
                    itemCount: data.length,
                    itemBuilder: (context, index) {
                      final point = data[data.length - 1 - index];
                      final value = _getValueAsDouble(point.value, metric.type);
                      return Card(
                        child: ListTile(
                          title: Text(
                            '${value.toStringAsFixed(1)} ${metric.unit}',
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                          subtitle: Text(
                              // dateFormat.format(point.dateFrom),
                              Utils.getMonthDayYearDateFormatted(point.dateFrom)
                              // dateFormat.format(point.dateFrom),
                              ),
                          trailing: Icon(
                            value >= metric.minHealthyValue && value <= metric.maxHealthyValue ? Icons.check_circle : Icons.warning,
                            color: value >= metric.minHealthyValue && value <= metric.maxHealthyValue ? AppColors.textColor : Colors.orange,
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ] else
                Center(
                  child: Text(
                    'No data available',
                    style: TextStyle(color: Colors.grey[600]),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  // Add this helper method to the _HealthDashboardState class
  double _getValueAsDouble(HealthValue value, HealthDataType type) {
    if (value is NumericHealthValue) {
      // if(type == HealthDataType.BLOOD_OXYGEN) {
      //   return (value.numericValue.toDouble() * 100);
      // } else {
      return value.numericValue.toDouble();
      // }
    }
    return 0.0;
  }
}
