import 'package:agrilink_vocpro/features/home/widgets/graphic_error_widget.dart';
import 'package:flutter/material.dart';
import 'package:bootstrap_icons/bootstrap_icons.dart';
import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
import 'package:agrilink_vocpro/core/constant/app_constant.dart';
import 'package:agrilink_vocpro/core/constant/app_theme.dart';
import 'package:agrilink_vocpro/core/state/result_state.dart';
import 'package:agrilink_vocpro/core/widgets/show_info.dart';
import 'package:agrilink_vocpro/features/home/detail_pages/soil_temperature/provider/soil_temp_provider.dart';
import 'package:agrilink_vocpro/features/home/widgets/graphic_widget.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gauge_indicator/gauge_indicator.dart';

class SoilTemperatureScreen extends StatelessWidget {
  const SoilTemperatureScreen({
    super.key,
    this.npk1Temperature = 0,
    this.npk2Temperature = 0,
  });

  final double npk1Temperature;
  final double npk2Temperature;

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => SoilTempProvider(),
      child: DefaultTabController(
        length: 2,
        child: Scaffold(
          appBar: AppBar(
            title: Text('Soil Temperature', style: AppTheme.labelMedium),
            centerTitle: true,
            backgroundColor: Colors.white,
            scrolledUnderElevation: 0,
            actions: const [
              Padding(
                padding: EdgeInsets.only(right: 16),
                child: Icon(
                  BootstrapIcons.water,
                  color: Colors.green,
                ),
              )
            ],
            bottom: const TabBar(
              tabs: [
                Tab(text: 'NPK 1'),
                Tab(text: 'NPK 2'),
              ],
            ),
          ),
          body: TabBarView(
            children: [
              buildTabContent(context, npk1Temperature, 'NPK 1', true),
              buildTabContent(context, npk2Temperature, 'NPK 2', false),
            ],
          ),
        ),
      ),
    );
  }

  // Generalized method for tab content to avoid duplication
  SafeArea buildTabContent(
      BuildContext context, double value, String label, bool isNpk1) {
    return SafeArea(
      child: ListView(
        padding: EdgeInsets.all(16.w),
        children: [
          SizedBox(height: MediaQuery.of(context).size.height * 0.05),
          buildTemperatureInfo(context, value),
          SizedBox(height: 16.h),
          buildInfoRow(context),
          SizedBox(height: 16.h),
          buildTemperatureRange(),
          SizedBox(height: 16.h),
          const Text('Grafik'),
          SizedBox(height: 16.h),
          buildGraphicContent(context, isNpk1),
        ],
      ),
    );
  }

  Widget buildTemperatureInfo(BuildContext context, double value) {
    return SizedBox(
      height: 240.h,
      child: Stack(
        fit: StackFit.expand,
        children: [
          Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(height: 80.h),
                const Icon(BootstrapIcons.water, size: 32, color: Colors.green),
                Text(
                  '$value°C', // Display temperature
                  style: const TextStyle(
                    fontSize: 28,
                    fontWeight: FontWeight.bold,
                    color: Colors.black,
                  ),
                ),
              ],
            ),
          ),
          AnimatedRadialGauge(
            duration: const Duration(seconds: 2),
            curve: Curves.easeOut,
            value: value,
            axis: GaugeAxis(
              degrees: 240,
              min: 0,
              max: 56.7,
              style: GaugeAxisStyle(
                background: Colors.grey.shade100,
                thickness: 50,
              ),
              progressBar: const GaugeBasicProgressBar(
                gradient: GaugeAxisGradient(colors: [
                  Colors.blue,
                  Colors.orange,
                ]),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // Build the row with 'Low', 'Ideal', 'High' temperature containers
  Widget buildTemperatureRange() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        _buildInfoContainer('Low', '<20°C', Colors.blue),
        _buildInfoContainer('Ideal', '20-30°C', Colors.green),
        _buildInfoContainer('High', '>30°C', Colors.orange),
      ],
    );
  }

  // Reusable container builder
  Widget _buildInfoContainer(String label, String tempRange, Color color) {
    return Container(
      height: 100.h,
      width: 100.w,
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: color, width: 2),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(label, style: AppTheme.labelMedium.copyWith(color: color)),
          SizedBox(height: 8.h),
          Text(tempRange,
              style: AppTheme.labelMedium, textAlign: TextAlign.center),
        ],
      ),
    );
  }

  // Information row with IconButton
  Widget buildInfoRow(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          'Soil Temperature',
          style: AppTheme.labelMedium,
          textAlign: TextAlign.center,
        ),
        IconButton(
          iconSize: 20.r,
          color: Colors.blue,
          onPressed: () {
            showInfo(context, 'Soil Temperature', AppConstant.soilTempInfo);
          },
          icon: const Icon(BootstrapIcons.info_circle),
        ),
      ],
    );
  }

  // Generalized method to build the graphic content based on NPK type
  Widget buildGraphicContent(BuildContext context, bool isNpk1) {
    return AspectRatio(
      aspectRatio: 1.6.h,
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16.w),
          border: Border.all(color: Colors.grey.shade300, width: 1.w),
        ),
        child: Consumer<SoilTempProvider>(
          builder: (context, provider, child) {
            final dataState = provider.dataState;

            switch (dataState) {
              case ResultState.loading:
                return const Center(child: CupertinoActivityIndicator());
              case ResultState.hasData:
                return GarphicWidget(
                  gradientColors: const [Colors.cyan, Colors.amber],
                  hour: List.generate(
                    isNpk1
                        ? provider.dataFetchedNpk1.length
                        : provider.dataFetchedNpk2.length,
                    (index) => isNpk1
                        ? provider.dataFetchedNpk1[index].hour ?? 0
                        : provider.dataFetchedNpk2[index].hour ?? 0,
                  ),
                  data: List.generate(
                    isNpk1
                        ? provider.dataFetchedNpk1.length
                        : provider.dataFetchedNpk2.length,
                    (index) => isNpk1
                        ? provider.dataFetchedNpk1[index].soiltemperature ?? 0
                        : provider.dataFetchedNpk2[index].soiltemperature ?? 0,
                  ),
                  maxValue: 70,
                );
              case ResultState.error:
                return const GraphicErrorWidget(message: 'Terjadi Kesalahan');
              case ResultState.noData:
                return const GraphicErrorWidget(message: 'Tidak Ada Data');
              case ResultState.initial:
              default:
                return const SizedBox.shrink();
            }
          },
        ),
      ),
    );
  }
}
