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

class SoilMoistureScreen extends StatelessWidget {
  const SoilMoistureScreen(
      {super.key, this.moistureNpk1 = 0, this.moistureNpk2 = 0});

  final double moistureNpk1;
  final double moistureNpk2;

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => SoilMoistureProvider(),
      child: DefaultTabController(
        length: 2,
        child: Scaffold(
          appBar: AppBar(
            title: Text('Soil Moisture', 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, moistureNpk1, 'NPK 1', true),
              buildTabContent(context, moistureNpk2, 'NPK 2', false),
            ],
          ),
        ),
      ),
    );
  }

  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),
          buildSoilMoistureInfo(context, value),
          SizedBox(height: 16.h),
          buildInfoRow(context),
          SizedBox(height: 16.h),
          const Text('Grafik'),
          SizedBox(height: 16.h),
          buildGraphicContent(context, isNpk1),
        ],
      ),
    );
  }

  Widget buildSoilMoistureInfo(BuildContext context, double value) {
    return SizedBox(
      height: 280.h,
      child: Stack(
        fit: StackFit.expand,
        children: [
          Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Icon(BootstrapIcons.water, size: 32, color: Colors.blue),
                Text('$value %', style: AppTheme.headline1),
              ],
            ),
          ),
          RotatedBox(
            quarterTurns: 2,
            child: AnimatedRadialGauge(
              duration: const Duration(seconds: 3),
              curve: Curves.easeOut,
              value: value,
              axis: GaugeAxis(
                degrees: 360,
                min: 0,
                max: 100,
                pointer: null,
                style: GaugeAxisStyle(
                  background: Colors.grey.shade100,
                  thickness: 50,
                ),
                progressBar: GaugeBasicProgressBar(
                  gradient: GaugeAxisGradient(colors: [
                    Colors.blue.shade200,
                    Colors.blue,
                  ]),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

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

  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<SoilMoistureProvider>(
          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.blue],
                  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].soilhumidity ?? 0
                        : provider.dataFetchedNpk2[index].soilhumidity ?? 0,
                  ),
                  maxValue: 1,
                );
              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();
            }
          },
        ),
      ),
    );
  }
}
