import React,{useState,useEffect,useRef} 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, Alert, Animated, AppState, Keyboard,StyleSheet,ActivityIndicator, Appearance} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,getKPIFields} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath, ImageFolderPath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign, Entypo,Fontisto, FontAwesome, MaterialCommunityIcons} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';

import { CustomPicker } from '../components/CustomPicker';
import DateTimePickerModal from 'react-native-modal-datetime-picker';

function ReportDetailNew(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 animatedChoice=useRef(new Animated.Value(0)).current;
    
    const [processing, setProcessing] = useState(false);
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera,setShowSwitchCamera]= useState(false);

    const [AddVisibility, setAddVisibility] = useState([]);
    const [AddVisFormData, setAddVisFormData] = useState({});
    const [isAddVisPresent, setIsAddVisPresent] = useState(0);
    const [showAlert, setShowAlert] = useState(false);
    const [Companies, setCompanies] = useState([]);
    const [Categories, setCategories] = useState([]);
    const [SubCategories, setSubCategories] = useState([]);
    const [Brands, setBrands] = useState([]);
    const [DisplayList, setDisplayList] = useState([]);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const showCameraRef = React.useRef(false);
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);

    const [SelectedImg, setSelectedImg] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [reCapImgModalObj, setReCapImgModalObj] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [ImgMadCount, setImgMadCount] = useState({img1:0,img2:0});

    const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
     const [selectedDate, setSelectedDate] = useState(null);

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef=React.useRef(AddVisibility);
    const StoreIdRef=React.useRef(null);
    const ScreenNameRef=React.useRef('');

    const VisFormDataRef=React.useRef(AddVisFormData);
    const isAddVisPresentRef=React.useRef(isAddVisPresent)

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
   
    const [data, setData] = useState([]);
    const [groupedData, setGroupedData] = useState([]);
    const [uniqueBrandData,  setUniqueBrandData] = useState([]);

    const [overall, setOverAll] = useState([]);  
    const [subCategory, setSubCateogry] = useState([]);  
    const [detailed, setDetailed] = useState([]);  

    const [loading, setLoading] = useState(false);
    const [daburSummary, setDaburSummary] = useState({ total: 0, available: 0 });
    
//  let jsonData ={
//   "status": 1,
//   "output": {
//     "store_id": "2418.0",
//     "category_id": "3d7242a8-19c4-4417-8b76-2e87abb1e52b",
//     "visit_date": "2024-12-25",
//     "shop_msl_score": null,
//     "shop_sos_score": 2.0,
//     "report": {
//       "overall": [
//         {
//           "kpi_name": "MSL",
//           "value": "0%"
//         },
//         {
//           "kpi_name": "SOS",
//           "value": "70%"
//         }
//       ],
//       "detailed": [
//         {
//           "kpi_level": "sub_category",
//           "data": [
//             {
//               "sub_category": "Muesli",
//               "data": [
//                 {
//                   "kpi_name": "MSL",
//                   "kpi_type": "presence",
//                   "sub_category_score": "0%",
//                   "data": [
//                     {
//                       "present_skus": [
                        
//                       ]
//                     },
//                     {
//                       "absent_skus": [
                        
//                       ]
//                     }
//                   ]
//                 },
//                 {
//                   "kpi_name": "SOS",
//                   "kpi_type": "share of shelf",
//                   "self_brand_subcategory_score": "81%",
//                   "data": [
//                     {
//                       "brand_name": "Kelloggs",
//                       "value": "81%",
//                       "facings": 21,
//                       "metadata": {
                        
//                       }
//                     },
//                     {
//                       "brand_name": "Yoga Bar",
//                       "value": "19%",
//                       "facings": 5,
//                       "metadata": {
                        
//                       }
//                     }
//                   ]
//                 }
//               ]
//             },
//             {
//               "sub_category": "Corn",
//               "data": [
//                 {
//                   "kpi_name": "MSL",
//                   "kpi_type": "presence",
//                   "sub_category_score": "0%",
//                   "data": [
//                     {
//                       "present_skus": [
                        
//                       ]
//                     },
//                     {
//                       "absent_skus": [
                        
//                       ]
//                     }
//                   ]
//                 },
//                 {
//                   "kpi_name": "SOS",
//                   "kpi_type": "share of shelf",
//                   "self_brand_subcategory_score": "77%",
//                   "data": [
//                     {
//                       "brand_name": "Aarambh",
//                       "value": "23%",
//                       "facings": 7,
//                       "metadata": {
                        
//                       }
//                     },
//                     {
//                       "brand_name": "Kelloggs",
//                       "value": "77%",
//                       "facings": 23,
//                       "metadata": {
                        
//                       }
//                     }
//                   ]
//                 }
//               ]
//             },
//             {
//               "sub_category": "Chocos",
//               "data": [
//                 {
//                   "kpi_name": "MSL",
//                   "kpi_type": "presence",
//                   "sub_category_score": "0%",
//                   "data": [
//                     {
//                       "present_skus": [
                        
//                       ]
//                     },
//                     {
//                       "absent_skus": [
                        
//                       ]
//                     }
//                   ]
//                 },
//                 {
//                   "kpi_name": "SOS",
//                   "kpi_type": "share of shelf",
//                   "self_brand_subcategory_score": "82%",
//                   "data": [
//                     {
//                       "brand_name": "Kelloggs",
//                       "value": "82%",
//                       "facings": 33,
//                       "metadata": {
                        
//                       }
//                     },
//                     {
//                       "brand_name": "Kwality",
//                       "value": "18%",
//                       "facings": 7,
//                       "metadata": {
                        
//                       }
//                     }
//                   ]
//                 }
//               ]
//             },
//             {
//               "sub_category": "Oats",
//               "data": [
//                 {
//                   "kpi_name": "MSL",
//                   "kpi_type": "presence",
//                   "sub_category_score": "0%",
//                   "data": [
//                     {
//                       "present_skus": [
                        
//                       ]
//                     },
//                     {
//                       "absent_skus": [
                        
//                       ]
//                     }
//                   ]
//                 },
//                 {
//                   "kpi_name": "SOS",
//                   "kpi_type": "share of shelf",
//                   "self_brand_subcategory_score": "45%",
//                   "data": [
//                     {
//                       "brand_name": "Aarambh",
//                       "value": "5%",
//                       "facings": 2,
//                       "metadata": {
                        
//                       }
//                     },
//                     {
//                       "brand_name": "Bagrrys",
//                       "value": "41%",
//                       "facings": 18,
//                       "metadata": {
                        
//                       }
//                     },
//                     {
//                       "brand_name": "Kelloggs",
//                       "value": "45%",
//                       "facings": 20,
//                       "metadata": {
                        
//                       }
//                     },
//                     {
//                       "brand_name": "Saffola",
//                       "value": "9%",
//                       "facings": 4,
//                       "metadata": {
                        
//                       }
//                     }
//                   ]
//                 }
//               ]
//             },
//             {
//               "sub_category": "Others",
//               "data": [
//                 {
//                   "kpi_name": "MSL",
//                   "kpi_type": "presence",
//                   "sub_category_score": "0%",
//                   "data": [
//                     {
//                       "present_skus": [
                        
//                       ]
//                     },
//                     {
//                       "absent_skus": [
                        
//                       ]
//                     }
//                   ]
//                 },
//                 {
//                   "kpi_name": "SOS",
//                   "kpi_type": "share of shelf",
//                   "self_brand_subcategory_score": "100%",
//                   "data": [
//                     {
//                       "brand_name": "Kelloggs",
//                       "value": "100%",
//                       "facings": 4,
//                       "metadata": {
                        
//                       }
//                     }
//                   ]
//                 }
//               ]
//             }
//           ]
//         }
//       ]
//     },
//     "images": [
//       {
//         "shelf_type": "Primary Shelf",
//         "raw_images": [
//           {
//             "url": "https://view.shelfwatch.io/?url=https://storage.googleapis.com/pd-sw-prod-us-core-sw2/dist/test_images_modified/e0b92c12-8cfe-473f-bdf6-d4b4ee2c1ee3_169806/9bf3afbf-b8da-44a1-b30e-1827572b1e1a_1.jpg",
//             "metadata": {
              
//             }
//           },
//           {
//             "url": "https://view.shelfwatch.io/?url=https://storage.googleapis.com/pd-sw-prod-us-core-sw2/dist/test_images_modified/e0b92c12-8cfe-473f-bdf6-d4b4ee2c1ee3_169806/a3194f19-5032-480d-b479-1f2a3fb275bd_1.jpg",
//             "metadata": {
              
//             }
//           }
//         ],
//         "stitched_images": [
//           {
//             "url": "https://view.shelfwatch.io/?url=https://storage.googleapis.com/pd-sw-prod-us-core-sw2//mnt/gcp/dist/analytics_stitch/stitched_images/1012/1bbb33d8006f49ad8554062744503273.jpg",
//             "metadata": {
              
//             }
//           }
//         ]
//       }
//     ]
//   }
// }

// const myJSON = JSON.stringify(jsonData);

// console.log("checkjson--",myJSON);

    useEffect(() => {
        StatusBar.setBarStyle('dark-content');
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        let cameraAllow=storeData1.CameraAllow=='true' || storeData1.CameraAllow==1?true:false;
        setStoreCameraAllow(cameraAllow);
          
        let isAdhoc=params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        StoreIdRef.current=storeData1.StoreId
        ScreenNameRef.current=menu1.ScreenName
        getData(storeData1,menu1);

        // const AppStateSubscription = AppState.addEventListener('change', (pro)=>{ _handleAppStateChange(pro)});
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        
        return function cleanup() {
            // AppStateSubscription.remove();
            return unsubscribe;
        };
    }, []);



    const showDatePicker = () => {
      setDatePickerVisibility(true);
    };

    const hideDatePicker = () => {
      setDatePickerVisibility(false);
    };
  
    const handleConfirm = (date) => {
      setSelectedDate(date); // Save the selected date in state
      hideDatePicker();
    };

    
    function  onBeforeRemove(e){
        if(showCameraRef.current==true){
            e.preventDefault();
            BgShowCamera(false);
        }
        else{
            if (hasUnsavedChangesRef.current==true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else{
                return;
            }  
        } 
    }
    
    function onRemoveScreen(e){     
        Alert.alert(
            "",
            "Do you really want to exit the screen?",
            [
              {
                text: "Cancel",
                onPress: () => {},
                style: "cancel"
              },
              { text: ST.OK, onPress: async () => {
                BgUnsavedChanges(false)
                await clear_item('storeData')
                // setHasUnsavedChanges(false);
                props.navigation.dispatch(e.data.action);} }
            ]
          );
    }
    
    function BgUnsavedChanges(val){
        hasUnsavedChangesRef.current=val
        setHasUnsavedChanges(val);
    }

    function BgShowCamera(val){
        showCameraRef.current=val
        setShowCamera(val);
    }
    
    function BgWindowData(val){
        WindowDataRef.current=val
        setAddVisibility(val);
    }

    function BgAddVisFormData(val){
        VisFormDataRef.current=val
        setAddVisFormData(val);
    }

  
    

    async function getData(storeData1,menu1){        
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
            
            let AllKPIFields=await getKPIFields(menu1);
            setKPIFields(AllKPIFields);
        

          

            await db.transaction(async function (txn) {        
                
                let q4=`SELECT StoreId,StoreName from Mapping_JourneyPlan UNION SELECT StoreId,StoreName FROM Adhoc_JourneyPlan`;

                await txn.executeSql(q4,[],async function (txn2, txnres2) { 
                    if(txnres2.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            arr.push(data);
                            if(i==txnres2.rows.length-1){setCompanies(arr);}                                
                        }
                    }
                },function (txnE,txnerr) { console.log(txnerr); },);

                let q2=`Select Distinct CategoryId,CategoryName from Master_Category`;
                await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                    if(txnres2.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            arr.push(data);
                            if(i==txnres2.rows.length-1){setCategories(arr);}                                
                        }
                    }
                },function (txnE,txnerr) { console.log(txnerr); },);

                  

            });          
        } catch (err) {
          console.log(err);          
        }        
    }

    async function validateForm(){
        let isValid=true;
        let {StoreName,StoreId,CategoryName,CategoryId,SubCategoryName,SubCategoryId,BrandName,BrandId,DisplayName,DisplayId,Remark,Image1,Image1Path}=AddVisFormData;
        
        let AddVisCameraReqI=KPIFields.findIndex(i=>i.KPIFieldName=='CompVisCameraReq');
        let AddVisCameraReqObj=AddVisCameraReqI>=0?KPIFields[AddVisCameraReqI]:{};
        let CompVisCameraReq=AddVisCameraReqI>=0?AddVisCameraReqObj['KPIFieldEnable']:true;



     if((StoreName=='' || StoreName==null )|| (StoreId=='' || StoreId==null)){
            isValid=false;
            notify('Please select Store Name','SHORT');
        }
      else if((CategoryName=='' || CategoryName==null )|| (CategoryId=='' || CategoryId==null)){
            isValid=false;
            notify('Please select category','SHORT');
        }
        else if(selectedDate=='' || selectedDate==null)
       {
        isValid=false;
        notify('Please select date','SHORT');
       }
        
    
        console.log('isValid:',isValid);
        return isValid;
    }


    function onselectionChange(option,keyLbl,keyVal,otherData){
        console.log('checkselection',option)
        let CompanyId=otherData.CompanyId!=null?otherData.CompanyId:'';
        let data=AddVisFormData;
        data[keyVal]=option.value;
        data[keyLbl]=option.label;
        BgAddVisFormData(data)
        BgUnsavedChanges(true)
        CleanSelector(option,keyLbl,data,CompanyId)
        setrerenderdata(!rerenderdata);     
    }

    function CleanSelector(option,keyLbl='',data={},CompanyId){

        if(keyLbl=='Company'){
            loadData(option.value,'Categories');

            data['CategoryId']='';
            data['CategoryName']='';
            data['SubCategoryId']='';
            data['SubCategoryName']='';
            data['BrandId']='';
            data['BrandName']='';

            data['DisplayId']=''
            data['DisplayName']=''

            data['Image1Path']=''

            data['Remark']=''
        }
        else if(keyLbl=='CategoryName'){
            console.log('CompanyId:',CompanyId);
            loadData(option.value,'SubCategories',CompanyId);

            data['SubCategoryId']='';
            data['SubCategoryName']='';
            data['BrandId']='';
            data['BrandName']='';

            data['DisplayId']=''
            data['DisplayName']=''

            data['Image1Path']=''

            data['Remark']=''
        }
        else if(keyLbl=='SubCategoryName'){
            console.log('CompanyId:',CompanyId);
            loadData(option.value,'Brands',CompanyId);

            data['BrandId']='';
            data['BrandName']='';

            data['DisplayId']=''
            data['DisplayName']=''

            data['Image1Path']=''

            data['Remark']=''
        }else if(keyLbl=='BrandName'){

            // clear brand

            data['DisplayId']=''
            data['DisplayName']=''

            data['Image1Path']=''

            data['Remark']=''

        }else if(keyLbl=='DisplayName'){

            // clear brand

            data['Image1Path']=''

            data['Remark']=''

        }
        setrerenderdata(!rerenderdata);
        }

    async function loadData(qId,type,CompanyId){
        try {   
        await db.transaction(async function (txn) { 
            let q='';
             if(type=='Categories') q=`select distinct CategoryId,CategoryName from Master_Competitor where (CompanyId ='${qId}' or CompanyId = ${qId}) order by CategoryName`;
            else if(type=='SubCategories') q=`Select Distinct p.SubCategoryId,p.SubCategoryName from Product_Master p where (p.CategoryId='${qId}' or p.CategoryId=${qId}) and (CompanyId ='${CompanyId}' or CompanyId = ${CompanyId}) order by p.SubCategorySequence`;
            else if(type=='Brands') q=`Select Distinct p.BrandName,p.BrandId from Product_Master p Where (p.SubCategoryId='${qId}' or p.SubCategoryId=${qId}) and (CompanyId ='${CompanyId}' or CompanyId = ${CompanyId}) order by p.BrandSequence`;
        
            await txn.executeSql(q,[],async function (txn2, txnres2) { 
                if(txnres2.rows.length>0){
                    let arr=[];
                    for(var i=0;i<txnres2.rows.length;i++){
                        let data =txnres2.rows.item(i);
                        arr.push(data);
                        if(i==txnres2.rows.length-1){
                            if(type=='Categories') setCategories(arr);
                            else if(type=='SubCategories')setSubCategories(arr);
                            else if(type=='Brands')setBrands(arr);
                        }                                
                    }
                }
            },function (txnE,txnerr) { console.log(txnerr); },);
           
          });          
        } catch (err) {
          console.log(err);          
        }
    }

     
    const fetchData = async () => {
        let isValid = await validateForm();
        if (isValid) {
            setProcessing(true);
            console.log('Fetching--', AddVisFormData.StoreId);
            let storeId = AddVisFormData.StoreId;
            // console.log("aaaaa", storeId);
            let categoryName = AddVisFormData.CategoryName;
            let v_date = selectedDate;
    
            const [month, day, year] = v_date.toLocaleDateString().split('/');
            const fullYear = year.length === 2 ? `20${year}` : year;
            const formattedDate = `${fullYear}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`;
            const visitdate = formattedDate;
    
            const visit_date = visitdate;
            const store_id = storeId;
            const category_name = categoryName;
    
            const auth_token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9qZWN0X2lkIjoiYWIyNmE1NDktMTA3YS00MTkyLTk1YTAtZDM1MzRlMWY4YjNhIn0.DcX-VA-1yCXoJd1WNdhFfTg-PZeNzqQE7NjsRkMrlC8';
            const myHeaders = new Headers();
            myHeaders.append("auth-token", auth_token);
    
            const requestOptions = {
                method: "GET",
                headers: myHeaders,
                redirect: "follow",
            };
    
            try {
                const response = await fetch(
                    `https://apis.shelfwatch.io/dabur_insights?visit_date=${visit_date}&store_id=${store_id}&category_name=${category_name}&project_id=ab26a549-107a-4192-95a0-d3534e1f8b3a`,
                    requestOptions
                );
    
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
    
                const result = await response.json();
    
                // Check if result is 1, then set data, otherwise set empty array
                if (result?.status === 1) {
                    // Set the fetched data to state if status is 1
                    setData(result?.output || []);
                    console.log('Original data---', result?.output);
    
                    const groupedData = result?.output?.filter(item => item['Shelf'] === 'Primary Shelf') || [];
                    console.log('Grouped data---', groupedData);
                    setGroupedData(groupedData);
    
                    const uniqueBrands = Array.from(
                        new Map(groupedData.map(item => [item.Brand, item])).values()
                    );
                    console.log('Unique brands---', uniqueBrands);
                    setUniqueBrandData(uniqueBrands);
    
                    // Calculate summary for Dabur
                    const daburItems = groupedData.filter(item => item.Brand === "Dabur");
                    const total = daburItems.length;
                    const available = daburItems.filter(item => item["On Shelf Availability"] === 1).length;
    
                    setDaburSummary({ total, available });
                } else {
                    // If result status is not 1, set empty data or some default value
                    setData([]);
                    setGroupedData([]);
                    setUniqueBrandData([]);
                    setDaburSummary({ total: 0, available: 0 });
                    console.log('No data available');
                }
    
            } catch (error) {
                console.error("Error fetching data:", error);
            } finally {
                setProcessing(false);
            }
        }
    };


 const fetchIRnewReportData = async () => {
  let isValid = await validateForm();
  if(isValid){
    setProcessing(true);
    //  let storeId = AddVisFormData.StoreId;
    //  console.log("aaaaa", storeId);
    //let categoryName = AddVisFormData.CategoryName;
    console.log("categoryiddd->",AddVisFormData.categoryId);
    
    let v_date = selectedDate;
    const [month, day, year] = v_date.toLocaleDateString().split('/');
    const fullYear = year.length === 2 ? `20${year}` : year;
    const formattedDate = `${fullYear}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`;
    const visitdate = formattedDate;

    const visit_date = visitdate;
    console.log("visit_date",visit_date)
    // const store_id = storeId;
    // const category_name = categoryName;


 
   const storeId = "2202";
   const categoryId = "3d7242a8-19c4-4417-8b76-2e87abb1e52b";
   const projectId = "e0b92c12-8cfe-473f-bdf6-d4b4ee2c1ee3";

  const url = `https://apis.shelfwatch.io/get_kelloggs_insights?visit_date=${visit_date}&store_id=${storeId}&category_id=${categoryId}&project_id=${projectId}`;

  try {
    const response = await fetch(url);
    const json = await response.json();
    if (json.status === 1) {
      setProcessing(false);
      const overall = json.output.report.overall; // MSL & SOS
    //  const detailed = json.output.report.detailed[0].data; // Array of subcategories
      const detailed = json.output.report.detailed.flatMap(item => item.data || []);; // Array of subcategories
     // const subCategory = json.output.report.detailed[0].kpi_level; // "sub_category"
      setOverAll(overall);
      setSubCateogry(subCategory);
      setDetailed(detailed)

      console.log("Overall:", overall);
      console.log("Subcategory Level:", subCategory);
      console.log("Detailed Subcategories:", detailed);
    } else {
      setProcessing(false);
      setOverAll([]);
      setSubCateogry([]);
      setDetailed([])

    }
  } catch (error) {
    setProcessing(false);
    console.error("Error fetching report:", error);
  }

  }
 
};
 

const _render_newIR_report = () => {
//   const overall = jsonData.output.report.overall;
//   const detailed = jsonData.output.report.detailed[0].data;
//   const subCategory = jsonData.output.report.detailed[0].kpi_level;

const renderSubCategory = ({ item }) => (
     <> 
      <View
    style={{
      marginBottom: 16,
      borderWidth: 1,
      borderColor: '#ccc',
      borderRadius: 10,
      overflow: 'hidden',
      marginTop:10,
      marginLeft:10,
      marginRight:10,
      backgroundColor: '#fff',
    }}
  >
    {/* Sub-category Header */}
    <View style={{ backgroundColor: '#eee', padding: 12 }}>
      <Text style={{ fontSize: 16, fontWeight: '700' }}>{item.sub_category}</Text>
    </View>

    {/* KPI Rows */}
    {item.data.map((kpi, kpiIdx) => (
      <View
        key={kpiIdx}
        style={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
          paddingVertical: 10,
          paddingHorizontal: 15,
          borderBottomWidth: kpiIdx === item.data.length - 1 && !item.data.some(k => k.kpi_name === 'SOS') ? 0 : 1,
          borderColor: '#e0e0e0',
        }}
      >
        <Text style={{ fontWeight: '500' }}>{kpi.kpi_name}</Text>
        <Text>{kpi.sub_category_score || kpi.self_brand_subcategory_score}</Text>
      </View>
    ))}

    {/* SOS Brand Block (only if exists) */}
    {item.data.map((kpi, kpiIdx) => (
      kpi.kpi_name === 'SOS' && kpi.data && (
        <View
          key={`sos-${kpiIdx}`}
          style={{
            paddingVertical: 12,
            paddingHorizontal: 15,
            borderTopWidth: 1,
            borderColor: '#e0e0e0',
            backgroundColor: '#f9f9f9',
          }}
        >
          <Text style={{ fontSize: 15, fontWeight: '600', marginBottom: 8 }}>Brand Details</Text>
          {[...kpi.data].sort((a, b) => (a.brand_name === 'Kelloggs' ? -1 : b.brand_name === 'Kelloggs' ? 1 : 0))
          .map((brand, brandIdx) => (
            <View
              key={brandIdx}
              style={{
                flexDirection: 'row',
                justifyContent: 'space-between',
                marginBottom: 6,
              }}
            >
              <Text style={{ fontSize: 13, flex: 1 }}>• {brand.brand_name}</Text>
              <Text style={{ fontSize: 13 }}>{brand.value}</Text>
            </View>
          ))}
        </View>
      )
    ))}
  </View>

     </>
 
);

  return (
    <>
     <View style={[customStyle.addvisCon]}>
                <View style={[customStyle.addvis_pCon]}>
                        <View style={customStyle.addvis_pChoiceBoxCon}>
                        </View>
                        
                </View>
              
                <View style={customStyle.addVisForm}>
                    <View style={customStyle.addVisRow}>
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol1]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>Store name</Text>
                                {CustomPicker(props,Companies,'StoreName','StoreId','StoreName','StoreId',onselectionChange,{value:AddVisFormData.StoreName,otherData:{}})}
                            </View>
                        </View>
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol2]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>Category</Text>

                                {CustomPicker(props,Categories,'CategoryName','CategoryId','CategoryName','CategoryId',onselectionChange,{value:AddVisFormData.CategoryName,otherData:{}})}
                                
                            </View>
                        </View>                     
                         
                                    
                        <View style={[customStyle.addVisCol100]} >
                           
                          <View style={[customStyle.report_datePicker_con,{ flexDirection: 'row', alignItems: 'center',justifyContent:'space-between' }]}>
                                <Text style={customStyle.report_new_date}>Select Date</Text>

                                    <TouchableOpacity  style={[customStyle.repoertDetailsPicker]} onPress={showDatePicker}>
                                    <Fontisto style={{marginTop:10,marginRight:12}} name='date' size={20}  color={'blue'} />  
                                     </TouchableOpacity>
                                                                         
                            </View>
                        {selectedDate && (<Text style={{ marginTop: 20,backgroundColor:'#eaf3fa', borderRadius:4, padding:12,fontWeight:20,color:'black' }}>Selected Date: {selectedDate.toLocaleDateString()}</Text>)}
                        <DateTimePickerModal isVisible={isDatePickerVisible}  mode="date" onConfirm={handleConfirm}  onCancel={hideDatePicker} />
                         </View>

                        
                        <View style={customStyle.addVis_btnWrap}>
                            <TouchableOpacity style={customStyle.addVis_btn} onPress={()=>{fetchIRnewReportData()}}>
                                <Text style={customStyle.addVisBtnText}>Go</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
              
                </View>
                {
               (rerenderdata== rerenderdata) && 
                <ScrollView contentContainerStyle={customStyle.addVisScrollCon} style={customStyle.reportIrScroll}>
                <View style={customStyle.addVis_list}>
                    <Text style={customStyle.ir_listhdrText}>Report Details</Text>
                    <View style={customStyle.addVis_listInner}>

                <View style={styles.container}>
            {/* Store Information */}
            {/* <View style={styles.storeInfo}>
               {
                AddVisFormData.StoreId && overall.length > 0 && 
                 <Text style={styles.infoText}>Store ID: {AddVisFormData.StoreId}</Text>
               }

               {
                AddVisFormData.StoreName && overall.length > 0 && 
                 <Text style={styles.infoText}>Store Name: {AddVisFormData.StoreName}</Text>
               }

               {
                AddVisFormData.CategoryName &&overall.length > 0 && 
                 <Text style={styles.infoText}>Category: {AddVisFormData.CategoryName}</Text>
               }
              
            </View>
               */}
            </View>
                  </View>
                </View>
                </ScrollView>
                }
            </View>
     
     <FlatList
      ListHeaderComponent={() => (
        <View style={{ padding: 10 }}>

        {overall.length>0 && (
            <>
               <Text style={{ fontWeight: 'bold', fontSize: 16, marginBottom: 8 }}>Store Category Score</Text>
          
       <View style={{ borderWidth: 1, borderColor: '#ccc', borderRadius: 6, overflow: 'hidden', marginBottom: 16, marginTop:10 }}>
       {overall.map((item, idx) => (
            <View key={idx} style={{ flexDirection: 'row', justifyContent: 'space-between',borderBottomColor: '#ddd',paddingVertical: 10,paddingHorizontal: 15, backgroundColor: idx % 2 === 0 ? '#f9f9f9' : '#fff', borderBottomWidth: idx === overall.length - 1 ? 0 : 1,}}>
              <Text style={{ fontWeight: '600' }}>{item.kpi_name}</Text>
              <Text>{item.value}</Text>
            </View>
          ))}
              
       </View>
            </>
        )}
       

          {/* Sub Category Score heading here */}
          {
            detailed.length>0 &&(
          <Text style={{ fontSize: 16, fontWeight: '700', marginTop: 3 }}>Sub Category Score</Text>
            )
          }

          
        </View>
      )}
      data={detailed}
      renderItem={renderSubCategory}
      showsVerticalScrollIndicator={false}
      keyExtractor={(item, index) => `${item.sub_category}_${index}`}
      contentContainerStyle={{ paddingHorizontal: 10, paddingBottom: 20 }}
    />

    </>
   
  );
};


    function _render_ir_report(){
        let xpos=0;
        if(animatedChoice!=null ){
            xpos=animatedChoice.interpolate({
                inputRange:[0,1],
                outputRange:[0,-75],
            });
        }

        let AddVisCameraReqI=KPIFields.findIndex(i=>i.KPIFieldName=='CompVisCameraReq');
        let AddVisCameraReqObj=AddVisCameraReqI>=0?KPIFields[AddVisCameraReqI]:{};
        let CompVisCameraReq=AddVisCameraReqI>=0?AddVisCameraReqObj['KPIFieldEnable']:true;
        return (
            <View style={[customStyle.addvisCon]}>
                <View style={[customStyle.addvis_pCon]}>
                        <View style={customStyle.addvis_pChoiceBoxCon}>
                        </View>
                        
                </View>
              
                <View style={customStyle.addVisForm}>
                    <View style={customStyle.addVisRow}>
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol1]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>Store name</Text>
                                {CustomPicker(props,Companies,'StoreName','StoreId','StoreName','StoreId',onselectionChange,{value:AddVisFormData.StoreName,otherData:{}})}
                            </View>
                        </View>
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol2]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>Category</Text>
                                {/* {CustomPicker(props,Categories,'CategoryName','CategoryId','CategoryName','CategoryId',onselectionChange,{value:AddVisFormData.CategoryName,otherData:{'CompanyId':AddVisFormData.CompanyId!=null?AddVisFormData.CompanyId:''}})} */}

                                {CustomPicker(props,Categories,'CategoryName','CategoryId','CategoryName','CategoryId',onselectionChange,{value:AddVisFormData.CategoryName,otherData:{}})}
                                
                            </View>
                        </View>                     
                         
                                    
                        <View style={[customStyle.addVisCol100]} >
                           
                          <View style={[customStyle.report_datePicker_con]}>
                                <Text style={customStyle.report_new_date}>Select Date</Text>

                                    <TouchableOpacity  style={[customStyle.repoertDetailsPicker]} onPress={showDatePicker}>
                                    <Fontisto name='date' size={20} color={'blue'} />  
                                     </TouchableOpacity>
                                                                         
                            </View>
                        {selectedDate && (<Text style={{marginTop:10,backgroundColor:'#eaf3fa', borderRadius:4, padding:12,fontWeight:20,color:'black' }}>Selected Date: {selectedDate.toLocaleDateString()}</Text>)}
                        <DateTimePickerModal isVisible={isDatePickerVisible}  mode="date" onConfirm={handleConfirm}  onCancel={hideDatePicker} />
                         </View>

                        
                        <View style={customStyle.addVis_btnWrap}>
                            <TouchableOpacity style={customStyle.addVis_btn} onPress={()=>{fetchData()}}>
                                <Text style={customStyle.addVisBtnText}>Go</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
              
                </View>
                {
               (rerenderdata== rerenderdata) && 
                <ScrollView contentContainerStyle={customStyle.addVisScrollCon} style={customStyle.reportIrScroll}>
                <View style={customStyle.addVis_list}>
                    <Text style={customStyle.addVis_listhdrText}>Report Details</Text>
                    <View style={customStyle.ir_listInner}>

                <View style={styles.container}>
            {/* Store Information */}
            <View style={styles.storeInfo}>
               {
                AddVisFormData.StoreId && uniqueBrandData.length > 0 && 
                 <Text style={styles.infoText}>Store ID: {AddVisFormData.StoreId}</Text>
               }

               {
                AddVisFormData.StoreName && uniqueBrandData.length > 0 && 
                 <Text style={styles.infoText}>Store Name: {AddVisFormData.StoreName}</Text>
               }

               {
                AddVisFormData.CategoryName &&uniqueBrandData.length > 0 && 
                 <Text style={styles.infoText}>Category: {AddVisFormData.CategoryName}</Text>
               }
                {/* <Text style={styles.infoText}>Store ID: {AddVisFormData.StoreId}</Text>
                <Text style={styles.infoText}>Store Name: {AddVisFormData.StoreName}</Text>
                <Text style={styles.infoText}>Category: {AddVisFormData.CategoryName}</Text> */}
                {/* <Text style={styles.infoText}>Category: Juices Nectar and Drinks</Text> */}
            </View>


             {uniqueBrandData.length > 0 && (
                <>
                <Text style={[styles.sectionHeader,{color:'#454545'}]}>Primary Shelf</Text>
                <View style={styles.table}>
                <Text style={[styles.tableSOS,{color:'#454545'}]} >Share of Shelf</Text>
                <View style={[styles.tableHeader,{color:'#454545'}]}>
                <Text style={[styles.tableHeaderText,{color:'#454545'}]}>Brand</Text>
                <Text style={[styles.tableHeaderText,{color:'#454545'}]}>SOS %</Text>
                </View>
                <FlatList
                    // data={groupedData}
                    data={uniqueBrandData}
                    keyExtractor={(item, index) => index.toString()}
                    renderItem={({ item }) => (
                        <View style={styles.tableRow}>
                            <Text style={styles.tableCell}>{item.Brand}</Text>
                            <Text style={styles.tableCell}>{item["SoS % (Brand Level)"]}</Text>
                        </View>
                    )}
                />
            </View>

            {/* {
                uniqueBrandData.length > 0 &&(
                    <>
                    <Text style={styles.sectionHeader}>Summary</Text>
                    <View style={styles.summaryContainer}>
                        <View style={styles.tableHeader}>
                            <Text style={styles.tableHeaderText}>Brand</Text>
                            <Text style={styles.tableHeaderText}>Availability</Text>
                        </View>
                        <View style={styles.tableRow}>
                            <Text style={styles.tableCell}>Dabur</Text>
                            <Text style={styles.tableCell}>{`${daburSummary.available} / ${daburSummary.total}`}</Text>
                        </View>
                    </View>

                    </>
                  
                )

            } */}
            <View style={[styles.summaryContainer,{padding:20}]}>
            <Text style={[styles.sectionHeader,{textAlign: 'center'}]}>On Shelf Availability</Text>
           
            <Text style={styles.tableHeaderText}>Summary</Text>
                    <View style={styles.summaryContainer}>
                        <View style={styles.tableHeader}>
                            <Text style={styles.tableHeaderText}>Brand</Text>
                            <Text style={styles.tableHeaderText}>Availability %</Text>
                        </View>
                        <View style={styles.tableRow}>
                            <Text style={styles.tableCell}>Dabur</Text>
                            <Text style={styles.tableCell}>{`${daburSummary.available} / ${daburSummary.total} (${parseInt(daburSummary.available*100/daburSummary.total)}%)`}</Text>
                        </View>
                    </View>


          <Text style={styles.tableHeaderText}>Details</Text>
            <View style={styles.table}>
                <View style={styles.tableHeader}>
                    <Text style={styles.tableHeaderText}>SKU</Text>
                    <Text style={styles.tableHeaderText}>Status</Text>
                </View>
                <FlatList
                    data={groupedData}
                    keyExtractor={(item, index) => index.toString()}
                    renderItem={({ item }) => (
                        <View style={styles.tableRow}>
                            <Text style={styles.tableCell}>{item["SKU Name"]}</Text>
                            <Text style={styles.tableCell}>{item["On Shelf Availability"] || '0'}</Text>
                        </View>
                    )}
                />
            </View>

            </View>
            <Text style={styles.sectionHeader}>Asset</Text>
            <View style={styles.table}>
            <Text style={styles.tableSOS} >Asset Presence</Text>
                <View style={styles.tableHeader}>
                    <Text style={styles.tableHeaderText}>Brand</Text>
                    <Text style={styles.tableHeaderText}>Asset Presence</Text>
                </View>
                <FlatList
                    data={uniqueBrandData}
                    keyExtractor={(item, index) => index.toString()}
                    renderItem={({ item }) => (
                        <View style={styles.tableRow}>
                            <Text style={styles.tableCell}>{item.Brand}</Text>
                            <Text style={styles.tableCell}>{item["Asset Presence"] || '0'}</Text>
                        </View>
                    )}
                />
            </View>
                </>
             )}                
            </View>
                  </View>
                </View>
                </ScrollView>
                }
            </View>
        )
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
         {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <View style={{zIndex: 10}}>
          {/* <CustomHeader {...props} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/> */}
          <CustomHeader {...props} title={(currentMenu.MenuName || currentMenu?.ReportName )||'Report'}/>
        </View>
         
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.roundScrollWrapper,customStyle.zIndex0]}>

         <View style={[customStyle.pageContentWrapper]}>
            {Object.keys(storeData).length == 10000 ? (
                <View style={customStyle.addVis_Wrapper}>
                {_render_ir_report()}
                </View>
            ) : (
                <View style={customStyle.addVis_Wrapper}>
                {_render_newIR_report()}
                </View>
            )}
            </View>

         
       </LinearGradient> 
        
      </Container>   
    ); 
}



const styles = StyleSheet.create({
    container: {
        flex: 1,
        padding: 1,
        backgroundColor: '#fff',
    },
    storeInfo: {
        marginBottom: 5,
    },
    infoText: {
        fontSize: 14,
        fontWeight: '500',
        marginBottom: 2,
        marginLeft:10,
        color:'#454545'
    },
    sectionHeader: {
        fontSize: 18,
        fontWeight: '700',
        marginVertical: 10,
        color:'#454545'
    },
    table: {
        borderWidth: 1,
        borderColor: '#ddd',
        marginBottom: 20,
    },
    tableSOS: {
        textAlign: 'center', // Centers text horizontally
        fontSize: 18, // Adjust the font size as needed
        fontWeight: 'bold', // Optional: Makes the text bold
        marginVertical: 10, // Adds space above and below the text
        color:'#454545'
    },
    tableHeader: {
        flexDirection: 'row',
        backgroundColor: '#f5f5f5',
        borderBottomWidth: 1,
        justifyContent: 'center',
        alignItems: 'center',
        alignSelf: 'center',
        textAlign: 'center',
        padding: 5,
        borderColor: '#ddd',
    },
    tableHeaderText: {
        flex: 1,
        fontSize: 16,
        fontWeight: '700',
        padding: 5,
        textAlign: 'center',
        color:'#454545'
    },
    tableRow: {
        flexDirection: 'row',
        borderBottomWidth: 1,
        borderColor: '#ddd',
    },
    tableCell: {
        flex: 1,
        fontSize: 14,
        padding: 5,
        textAlign: 'center',
        color:'#454545'
    },
    loadingContainer: { flex: 1, justifyContent: "center", alignItems: "center" },
    summaryContainer: { marginVertical: 20, borderWidth: 1, borderColor: "#ccc" },
});
  
  

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