import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/components/top_back_bar_app.dart';
import 'package:niogu_app/core/constants/app_color.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/utils/log_message.dart';
import 'package:niogu_app/core/enums/review_display_policy.dart';
import 'package:niogu_app/core/enums/review_display_type.dart';
import 'package:niogu_app/core/widgets/custom_snackbar.dart';
import 'package:niogu_app/features/online_store/domain/entities/online_store.dart';
import 'package:niogu_app/features/online_store/presentation/providers/online_store_provider.dart';
import 'package:sizer/sizer.dart';

class RatingConfigurationScreen extends ConsumerStatefulWidget {
  const RatingConfigurationScreen({super.key});

  @override
  ConsumerState<RatingConfigurationScreen> createState() =>
      _RatingConfigurationScreenState();
}

class _RatingConfigurationScreenState
    extends ConsumerState<RatingConfigurationScreen> {
  ReviewDisplayType _type = ReviewDisplayType.rating_only;

  ReviewDisplayPolicy _policy = ReviewDisplayPolicy.four_and_five_star_only;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) => _fetchConfiguration());
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  Future<void> _fetchConfiguration() async {
    try {
      final ratingConfiguration = await ref
          .read(onlineStoreRepositoryProvider)
          .fetchRatingConfiguration();

      _type = ratingConfiguration.type;
      _policy = ratingConfiguration.policy;
      setState(() {});
    } catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      CustomSnackbar.showError(context, "Ups, terjadi kesalahan");
      context.pop();
    }
  }

  Future<void> _ratingConfiguration() async {
    try {
      await ref
          .read(onlineStoreControllerProvider.notifier)
          .ratingConfiguration(
            RatingConfiguration(type: _type, policy: _policy),
          );

      if (!mounted) return;
      CustomSnackbar.showSuccess(
        context,
        "Pengaturan rating produk berhasil diperbarui",
      );
      context.pop();
    } catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      CustomSnackbar.showError(context, "Ups, terjadi kesalahan");
    }
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final bool isTablet = 100.w >= 600;

        final onlineStoreControllerState = ref.watch(
          onlineStoreControllerProvider,
        );

        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: const Color(0xFFF9FAFB),
            appBar: TopBackBarApp(
              title: "Atur Rating Produk",
              onTap: () => context.pop(),
            ),
            body: SingleChildScrollView(
              padding: EdgeInsets.all(5.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildSectionTitle(isTablet, "Jenis Tampilan Penilaian"),
                  _buildOptionCard(
                    isTablet: isTablet,
                    title: "Tampilkan Rating Saja",
                    subtitle: "Hanya menampilkan angka rata-rata bintang.",
                    value: ReviewDisplayType.rating_only,
                    groupValue: _type,
                    onChanged: (val) {
                      setState(() {
                        if (val is ReviewDisplayType) {
                          _type = val;
                        }
                      });
                    },
                    previewImage: "assets/images/preview_rating_only.png",
                  ),
                  _buildOptionCard(
                    isTablet: isTablet,
                    title: "Rating & Ulasan",
                    subtitle:
                        "Menampilkan bintang beserta teks ulasan pelanggan.",
                    value: ReviewDisplayType.rating_and_review,
                    groupValue: _type,
                    onChanged: (val) {
                      setState(() {
                        if (val is ReviewDisplayType) {
                          _type = val;
                        }
                      });
                    },
                    previewImage: "assets/images/preview_rating_comment.png",
                  ),

                  SizedBox(height: 4.h),

                  _buildSectionTitle(
                    isTablet,
                    "Kriteria Penilaian yang Muncul",
                  ),
                  _buildOptionCard(
                    isTablet: isTablet,
                    title: "Seluruh Rating",
                    subtitle:
                        "Menampilkan semua ulasan dari bintang 1 hingga 5.",
                    value: ReviewDisplayPolicy.all_rating,
                    groupValue: _policy,
                    onChanged: (val) {
                      setState(() {
                        if (val is ReviewDisplayPolicy) {
                          _policy = val;
                        }
                      });
                    },
                    previewImage: "assets/images/preview_all_stars.png",
                  ),
                  _buildOptionCard(
                    isTablet: isTablet,
                    title: "Bintang 4 & 5 Saja",
                    subtitle:
                        "Hanya ulasan positif yang tampil di toko online.",
                    value: ReviewDisplayPolicy.four_and_five_star_only,
                    groupValue: _policy,
                    onChanged: (val) {
                      setState(() {
                        if (val is ReviewDisplayPolicy) {
                          _policy = val;
                        }
                      });
                    },
                    previewImage: "assets/images/preview_good_stars.png",
                  ),

                  SizedBox(height: 3.h),
                  ElevatedButton(
                    onPressed: onlineStoreControllerState.isLoading
                        ? null
                        : _ratingConfiguration,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppColor.primaryColor,
                      minimumSize: Size(double.infinity, 7.h),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(3.w),
                      ),
                      disabledBackgroundColor: Colors.grey.shade300,
                    ),
                    child: Text(
                      "Simpan Konfigurasi",
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                        fontSize: AppFontSize.medium.sp,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildSectionTitle(bool isTablet, String title) {
    return Padding(
      padding: EdgeInsets.only(left: 1.w, bottom: 2.h),
      child: Text(
        title,
        style: TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: isTablet ? AppFontSize.medium.sp : AppFontSize.small.sp,
        ),
      ),
    );
  }

  Widget _buildOptionCard({
    required bool isTablet,
    required String title,
    required String subtitle,
    required dynamic value,
    required dynamic groupValue,
    required Function(dynamic) onChanged,
    required String previewImage,
  }) {
    return GestureDetector(
      onTap: () => onChanged(value),
      child: Container(
        margin: EdgeInsets.only(bottom: 2.h),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(3.w),
          border: Border.all(color: Colors.grey.shade200, width: 1),
        ),
        child: Column(
          children: [
            ListTile(
              leading: Radio<dynamic>(
                value: value,
                groupValue: groupValue,
                activeColor: AppColor.primaryColor,
                onChanged: onChanged,
              ),
              title: Text(
                title,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: isTablet
                      ? AppFontSize.medium.sp
                      : AppFontSize.small.sp,
                ),
              ),
              subtitle: Text(
                subtitle,
                style: TextStyle(
                  fontSize: isTablet
                      ? (AppFontSize.medium - 1.25).sp
                      : (AppFontSize.small - 1.25).sp,
                  color: Colors.grey.shade700,
                ),
              ),
            ),
            Container(
              height: 15.h,
              width: double.infinity,
              margin: EdgeInsets.fromLTRB(4.w, 0, 4.w, 4.w),
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.circular(2.w),
              ),
              child: Center(
                child: Icon(
                  Icons.image_outlined,
                  size: 10.w,
                  color: Colors.grey[400],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
