import React,{useState,useEffect} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,FlatList, Dimensions} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,DownloadData, getDownloadJson1} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl, db} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card} from 'react-native-paper';
import {AntDesign} from '../components/icons';
import { WebView } from 'react-native-webview';
import CustomLoader from '../components/CustomLoader';
import NoDataComponent from '../components/NoDataComponent';
import LinearGradient from 'react-native-linear-gradient';
import { getFolderName, getMethodName, METHODS } from '../constants/methodNames';
import { PieChart,BarChart } from 'react-native-chart-kit';

function ReportChart(props) { 
    const route = useRoute();
    const ST=props.StaticText || {};
    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
  
   
    const [processing, setProcessing] = useState(true);
    const [isDataFound, setisDataFound] = useState(false);
    const [reportData, setReportData] = useState([]);
    const [aggrData, setAggrData] = useState({});
    const [cols, setcols] = useState([]);
    const [colWidth, setColWidth] = useState('100%');
    const [currentReportMenu, setCurrentReportMenu] = useState({});
    const [designation, setDesignation] = useState('');
    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
        let params=props.route.params? props.route.params:{};
        let ReportMenu=params?.ReportData || {};

        console.log("ReportChart------------",ReportMenu)
        setCurrentReportMenu(ReportMenu);
        getData(ReportMenu);
    }, []);


    async function getData(ReportMenu){        
      try {
        
        let DownloadList=JSON.parse(ReportMenu?.DownloadKey);
        console.log("ReportChart------------1",DownloadList)
        if(DownloadList.length>0){
        await Promise.all(
          DownloadList.map(async (item,index) => {
            let allReportData= await DownloadReport(item);
            console.log('allReportData',allReportData,item);
            if(allReportData.length>0){
                let repotKey=item;
                repotKey["data"]=allReportData
                console.log("repotKey----",repotKey)
                setisDataFound(true);
                return repotKey
                //     setReportData(allReportData);
                // setProcessing(false);
                // setisDataFound(true);
            }
            else{
                notify('No data found');
                setisDataFound(false);
                setProcessing(false);
            }
          })
        ).then((res)=>{
          console.log("Directory is created successfully",res)
          setReportData(res);
          setProcessing(false);
          return
        });
        
      }
      } catch (err) {
        setProcessing(false);
        console.log(err);          
      }  
          
    }

    async function DownloadReport(ReportMenu){
        let downloadKey=ReportMenu.KeyName;
        let loginInfo = await get_item('loginInfo');
        const loginDetails = JSON.parse(loginInfo);
        const url=props.baseurl+getMethodName(METHODS.DOWNLOADJSON_METHOD);
        let data={
          Downloadtype:downloadKey,
          Username: loginDetails.UserId,
          Param1: '',
          Param2: Platform.OS=="ios"?"iOS":"Android",
        };
  
        console.log(url,data);
        return await getDownloadJson1(url,data)
        .then(async(res)=>{  
          if (res[downloadKey]) {
            let data_arr = res[downloadKey] || []; 
            return data_arr;
          }
          else{
            return [];
          }        
        })
        .catch((err)=>{
          console.log('onPage Team error',err);
          return [];
        }); 
    }


    let data=[
      {
        name: "OSA",
        score: 60,
        color: "#a29bfe",
        legendFontColor: "#000",
        legendFontSize: 15
      },{
        name: "total",
        score: 60,
        color: "#6c5ce7",
        legendFontColor: "#7F7F7F",
        legendFontSize: 15
      },]

      // const data1 = {
      //   labels: ["January", "February", "March", "April", "May", "June"],
      //   datasets: [
      //     {
      //       data: [20, 45, 28, 80, 99, 43]
      //     }
      //   ]
      // };
      // const data1=[
      //   {
      //     label: 'January',
      //     data: [10, 20, 30],
      //   },
      //   {
      //     label: 'February',
      //     data: [40, 50, 60],
      //   },
      //   {
      //     label: 'March',
      //     data: [70, 80, 90],
      //   },
      // ]

//       const minValue = 80;

// function* yLabel() {
//   yield* [minValue, 90, 100];
// }

// const datapoints = [89, 88, 96, 97, 94, 91, 88].map(
//   (datapoint) => datapoint - minValue - 1,
// );

const data1 = {
    labels: ["TotalAttempt", "RightAnswer"],
    datasets: [
      {
        data: [12, 6]  
      }
    ]
  };

// const data1 = {
//   labels: ['Sat', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
//   datasets: [
//     {
//       data: [89, 88, 96, 97, 94, 91, 88],
//     },
//   ],
// };


const screenWidth = Dimensions.get('window').width;
  // const yLabelIterator = yLabel();


    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader title={ST.Loading+"..."}/>}
        <CustomHeader {...props} showaddstore={true} title={'Report'}/>
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
        <View style={[customStyle.pageContentWrapper,customStyle.ImageTypesPageWrap]}>
            <View style={customStyle.ImageTypesLHd}>
                <Text  style={customStyle.ImageTypesLHdText}>{currentReportMenu.ReportName}</Text>
            </View>
          { !props?.isDataDownloaded && <NoDataComponent {...props}/>}
          { 
            <View>
              { isDataFound==false && 
                <View style={customStyle.noDataCon}>
                  <Text style={customStyle.noDataText}>{ST.NoDataAvailable}</Text>
                </View>
              }

              {
                
                <ScrollView
                  contentContainerStyle={[customStyle.rp_scrollViewInner,{paddingBottom:100}]}
                  style={customStyle.rp_scrollView}
                >
                  
                  <>
                  {reportData && reportData?.map((item)=>{
                    console.log("item?.data--------",item?.data)
                    let label=[];
                    let labelVal=[];
                    let barColor=[]
                    item && item?.data && item?.data?.map((item)=>{
                        label.push(item?.name)
                        labelVal.push(item?.score||0)
                        barColor.push(()=>item?.color)
                    })
    
                    const structData = {
                    labels: label,
                    datasets: [
                        {
                          data: labelVal,
                          colors: barColor,
                        },
                      ],
                    };

                    const dataWithPercentages = data?.map((item,i) => ({
                          name: item?.name,
                          score: (item?.score / 100) * 100,
                          color:item?.color
                        }));
                    return(
                      <>
                      <View style={[customStyle.vlUinfo_Card]}>                
                        <View style={[customStyle.vlUinfo_CardRow,customStyle.vlUinfo_CardBorder,{marginBottom:10}]}> 
                          <Text  style={[customStyle.ImageTypesLHdText,{color:"#636e72", fontWeight:"bold"}]}>{item?.Title}</Text>           
                        </View> 
                        {console.log("item---",item)}
                      {
                        item?.GraphType=="Pie" && item?.data && item?.data[0].hasOwnProperty("score") &&
                        <PieChart
                          data={item?.data||[]}
                          width={300}
                          height={120}
                          // chartConfig={chartConfig}
                          chartConfig={{
                            backgroundColor: "#e26a00",
                            backgroundGradientFrom: "#fb8c00",
                            backgroundGradientTo: "#ffa726",
                            decimalPlaces: 2, // optional, defaults to 2dp
                            color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
                            labelColor: (opacity = 1) => `rgb(255, 0, 0, ${opacity})`,
                            style: {
                              borderRadius: 16
                            },
                            propsForDots: {
                              r: "2",
                              strokeWidth: "2",
                              stroke: "#ffa726"
                            }
                          }}
                          accessor={"score"}
                          backgroundColor={"transparent"}
                          // paddingLeft={"15"}
                          center={[20,-10]}
                          absolute
                          />

                      }
                  {

                    item?.GraphType=="Column" && 
                    
                    <BarChart
                          style={{
                            borderColor:"#000000",
                            backgroundColor:"#d1d8e0",
                              // borderWidth:1,
                            // marginVertical: 2,
                            // marginHorizontal:0,
                            borderRadius: 16,
                          }}
                          data={structData}
                          segments={2}
                          width={screenWidth-50}
                          height={220}
                          verticalLabelRotation={0}
                          fromZero={true}
                          // showBarTops={false}
                          showBarTops={true}
                          // yAxisSuffix="%"
                          decorators={[
                              {
                                type: 'text',
                                position: 'top',
                                value: 'Top Label',
                              },
                            ]}
                          chartConfig={{
                            // backgroundColor: '#d1d8e0',
                            // backgroundGradientFrom: '#d1d8e0',
                            // backgroundGradientTo: '#d1d8e0',
                            decimalPlaces: 0, // optional, defaults to 2dp
                            // color: (opacity = 100) => `rgba(0, 255, 0, 100)`,
                            // labelColor: (opacity = 1) => `rgba(56, 103, 214, ${opacity})`,
                            backgroundGradientFrom: '#1E2923',
                            backgroundGradientTo: '#08130D',
                            color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
                            labelColor: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
                            style: {
                              // borderColor:"#000000",
                              // borderWidth:10,
                              // borderRadius: 30,
                            },
                            
                            fillShadowGradient:'#00cec9',
                            fillShadowGradientOpacity:1,
                            // showBarTops:false,
                            // formatYLabel: () => yLabelIterator.next().value,
                            // data: data.datasets,
                            // paddingRight: Number,
                            // useShadowColorFromDataset: true,
                            propsForDots: {
                              r: '0',
                              strokeWidth: '0',
                              stroke: '#000000',
                            },
                            yLabelFormatter: (value) => `${value}%`
                          }}
                          animation={{
                              duration: 2000,
                            }}
                            withCustomBarColorFromData={true}
                            // flatColor={true}
                        />
                        
                  }          
                  </View>              
                        </>
                    )
                  })
                            
                  }
                  </>
                </ScrollView>
              }
                
            </View>
          }
        </View>
        </LinearGradient>

      </Container>   
    ); 
  }
  
  

export default connect(mapStateToProps, mapDispatchToProps)(ReportChart);