import 'dart:math';

import 'package:flutter/material.dart';
import 'package:top_news_app/helper/helper.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:percent_indicator/percent_indicator.dart';
import 'package:top_news_app/localization/localization.dart';
import 'package:top_news_app/model/Polling.dart';
import 'package:top_news_app/providers/article_provider.dart';
import 'package:top_news_app/repos/exception_handlers.dart';

import '../services/article_service.dart';
import '../services/storage_service.dart';

class PollingCard extends StatefulWidget {
  final List<PollingData> polling;
  final PollingData poll;

  const PollingCard({
    super.key,
    required this.polling,
    required this.poll,
  });

  @override
  State<PollingCard> createState() => _PollingCardState();
}

class _PollingCardState extends State<PollingCard> {
  late bool result = false;
  late int index = 0;
  bool isLoading = false;
  int selectedValue = 1000;
  PollingData pollingData = PollingData();
  var articleService = ArticleService();
  var articleProvider = ArticleProvider();

  bool isAuth = false;
  var storage = StorageService();

  getTheIndex(){
    setState(() {
      isLoading = true;
    });

    if(widget.polling.isEmpty){
      pollingData = widget.poll;
    }else{
      Random random = Random();
      index = random.nextInt(widget.polling.length);
      pollingData = widget.polling[index];
    }

    for (int i = 0; i < pollingData.options!.length; i++){
      bool myVot = pollingData.options![i].youVot ?? false;
      if(myVot){
        selectedValue = pollingData.options![i].optionId!.toInt();
      }
    }

    setState(() {
      isLoading = false;
    });
  }

  voting(value) async{
    try{
      if(!isAuth){
        dialogLogin(context);
      }else{
        setState(() {
          selectedValue = value!.toInt();
        });
        var response = await articleService.setVoting(pollingData.id,value);
        var result = processResponse(response);
        if(result.containsKey('message')){
          showMessage(result['message']);
        }
        if(result['result']){
          await getThePollingValue();
        }else{
          selectedValue = 1000;
        }
      }
    }catch (e){
      selectedValue = 1000;
      rethrow;
    }

    setState(() {

    });
  }

  getThePollingValue() async{
    pollingData = await articleProvider.getSinglePolling(pollingData.id);
  }


  getAuthData() async{
    isAuth = (await storage.isAuthInLocal())!;
  }

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

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: elevation,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: isLoading ? const Padding(padding: EdgeInsets.all(40),
      child: Center(
          child: CircularProgressIndicator(),
      ),
      ) : Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '${pollingData.questions}',
              style: const TextStyle(
                fontSize: 18.0,
                fontWeight: FontWeight.bold,
              ),
            ),
            customSizeBox(10),
            GestureDetector(
              onTap: () {
                setState(() {
                  result = !result;
                });
              },
              child: Align(
                  alignment: Alignment.bottomRight,
                  child: Text(
                    getTranslated(context, 'See Result') ?? 'See Result',
                    style: GoogleFonts.robotoSerif(
                        color: primaryColors, fontWeight: FontWeight.w500),
                  )),
            ),
            const SizedBox(height: 18.0),
            Visibility(
              visible: result,
              child: Column(
                children: [
                  for (int i = 0; i < pollingData.options!.length; i++)
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '${pollingData.options?[i].option}',
                            style: const TextStyle(
                              fontSize: 18.0,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          customSizeBox(6),
                          LinearPercentIndicator(
                            width: MediaQuery.of(context).size.width -80,
                            animation: true,
                            lineHeight: 24.0,
                            animationDuration: 2000,
                            percent: pollingData.options?[i].totalVot?.toDouble() ?? 0.1,
                            center: Text("${pollingData.options?[i].totalVot}",style: GoogleFonts.robotoSerif(fontWeight: FontWeight.w600),),
                            progressColor: primaryColors,
                          ),
                        ],
                      ),
                    ),
                ],
              ),
            ),
            Visibility(
              visible: !result,
              child: Column(
                children: [
                  for (int i = 0; i < pollingData.options!.length; i++)
                    Container(
                      padding: const EdgeInsets.symmetric(vertical: 4),
                      child: RadioListTile(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8.0),
                          side: const BorderSide(color: primaryColors, width: 1.0),
                        ),
                        title: Text('${pollingData.options![i].option}'),
                        value: pollingData.options![i].optionId,
                        groupValue: selectedValue,
                        onChanged: (value) {
                          voting(value);
                        },
                      ),
                    ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
