import { View, Text, StyleSheet, Image, TouchableOpacity, Dimensions, TextInput, ScrollView, FlatList, Button, Alert, Modal, TouchableWithoutFeedback, StatusBar, ActivityIndicator, Platform } from 'react-native'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import RBSheet from 'react-native-raw-bottom-sheet';
import { styles } from './style';
import LinearGradient from 'react-native-linear-gradient';
import CustomHeader from '../../../components/CustomHeader';
import IMAGES from '../../../constants/Images';
import CustomButton from '../../../components/CustomButton';
import CustomDropdown from '../../../components/CustomDropdown';
import { GlobalTheme } from '../../../theme';
import { SafeAreaView } from 'react-native-safe-area-context';
import { BarChart } from 'react-native-gifted-charts';

import displayData from './display.json'
import { LineChart, PieChart, StackedBarChart } from 'react-native-chart-kit';
import { getDownloadJson } from '../../../constants/function';
import db, { getAllFromTable } from '../../../constants/database';
import { post } from '../../../api/ApiService';
import { ApiURL } from '../../../api/ApiConstant';
import mainDisplayData from './mainDisplay.json'
import axios from 'axios';
import Loader from '../../../constants/Loader';
import { useSelector } from 'react-redux';
import { useIsFocused } from '@react-navigation/native';
import moment from 'moment';
import _ from 'lodash';
import AsyncStorage from '@react-native-async-storage/async-storage';

// Latest code pushed by Ajeet
const visitedStoreData = [
   {
      id: 1,
      name: "Chawla Store",
      address: "G-8, Mahakavi Goswami Tulsidas Marg, Paraag Vihar, Press Colony, Hari Nagar, New Delhi, 110027",
      status: "pending"
   },
   {
      id: 2,
      name: "Mohan Mahalaxmi store",
      address: "G-8, Mahakavi Goswami Tulsidas Marg, Paraag Vihar, Press Colony, Hari Nagar, New Delhi, 110027",
      status: "completed"
   },
   {
      id: 3,
      name: "Bansal General store",
      address: "G-8, Mahakavi Goswami Tulsidas Marg, Paraag Vihar, Press Colony, Hari Nagar, New Delhi, 110027",
      status: "completed"
   }

];
const monthData = [
   { label: 'January', value: '1' },
   { label: 'February', value: '2' },
   { label: 'March', value: '3' },
   { label: 'April', value: '4' },
   { label: 'May', value: '5' },
   { label: 'June', value: '6' },
   { label: 'July', value: '7' },
   { label: 'August', value: '8' },
   { label: 'September', value: '9' },
   { label: 'October', value: '10' },
   { label: 'November', value: '11' },
   { label: 'December', value: '12' },
];
const yearData = [
   { label: '2025', value: '2025' },
   { label: '2024', value: '2024' },
   { label: '2023', value: '2023' },
   { label: '2022', value: '2022' },
   { label: '2021', value: '2021' },
   { label: '2020', value: '2020' },
   { label: '2019', value: '2019' },
   { label: '2018', value: '2018' },
   { label: '2017', value: '2017' },
   { label: '2016', value: '2016' },
   { label: '2015', value: '2015' },
];
const assetData = [
   {
      "section": "Asset%",
      "data": [
         { "display": "Real Endcap", "present": "No" },
         { "display": "Honey Parasite", "present": "Yes" },
         { "display": "Odonil Floor Stack", "present": "YHes" }
      ]
   },
   {
      "section": "Additional Visibility",
      "data": [
         { "display": "Active 1 Ltr Endcap", "present": "Yes" },
         { "display": "Chyawanprash Stack", "present": "Yes" }
      ]
   },
   {
      "section": "Promotion",
      "data": [
         { "display": "Activ 100% Juice", "present": "Yes" },
         { "display": "Airfresher", "present": "No" },
         { "display": "BABY CARE", "present": "No" },
         { "display": "Chyawanprash", "present": "No" },
         { "display": "Hair Oil", "present": "No" },
      ]
   }
]
const PieData = [
   {
      name: "Seoul",
      population: 21500000,
      color: "rgba(131, 167, 234, 1)",
      legendFontColor: "#7F7F7F",
      legendFontSize: 15
   },
   {
      name: "Toronto",
      population: 2800000,
      color: "#F00",
      legendFontColor: "#7F7F7F",
      legendFontSize: 15
   },
   {
      name: "Beijing",
      population: 527612,
      color: "red",
      legendFontColor: "#7F7F7F",
      legendFontSize: 15
   },
   {
      name: "New York",
      population: 8538000,
      color: "#ffffff",
      legendFontColor: "#7F7F7F",
      legendFontSize: 15
   },
   {
      name: "Moscow",
      population: 11920000,
      color: "rgb(0, 0, 255)",
      legendFontColor: "#7F7F7F",
      legendFontSize: 15
   }
];
const barData = {
   labels: ["Jan", "Feb", "March", "April",],
   datasets: [
      {
         data: [20, 45, 28, 80]
      }
   ]
};

const Dashboard = (props) => {

   const { navigation } = props;
   const screenHeight = Dimensions.get('screen').height;
   const screenWidth = Dimensions.get('screen').width;
   const [loading, setLoading] = useState(false)
   const refRBSheet = useRef();
   const [mainDisplayJson, setMainDisplayJson] = useState(mainDisplayData?.Tabs[0]?.MainTabData)
   const [isStoreSelected, setIsStoreSelected] = useState(false)
   const [searchResult, setSearchResult] = useState(false)
   const [storeData, setStoreData] = useState({})
   const [mainTab, setMainTab] = useState('mtd')
   const [activeTab, setActiveTab] = useState(mainDisplayJson?.subTabs?.[0]?.TabId || 1)
   const currentDate = new Date();
   const [year, setYear] = useState(currentDate.getFullYear());
   const [month, setMonth] = useState(currentDate.getMonth() + 1); // getMonth() returns 0-11

   const [filterData, setFilterData] = useState([]);
   const [stateOptions, setStateOptions] = useState([]);
   const [cityOptions, setCityOptions] = useState([]);
   const [asmOptions, setAsmOptions] = useState([]);

   const [state, setState] = useState(null);   // selected state ID
   const [city, setCity] = useState(null);     // selected city ID
   const [asmArea, setAsmArea] = useState(null); // selected ASM Area ID
   const [storeList, setStoreList] = useState([])
   const scrollViewRef = useRef(null);
   const [showButton, setShowButton] = useState(false);
   const [FeedBackModal, setFeedBackModal] = useState(false);
   const [LogoutModal, setLogoutModal] = useState(false);
   const [graphApiData, setGraphApiData] = useState({});
   const [searchText, setSearchText] = useState("")
   const [mainTabIndex, setMainTabIndex] = useState(0); // 0 = first tab
   const [mainTabs, setMainTabs] = useState(mainDisplayData.Tabs);
   const [showDetailsModal, setShowDetailsModal] = useState(false);
   const [selectedDetails, setSelectedDetails] = useState([]);
   const [modalGraphData, setModalGraphData] = useState({});

   const filteredGraphs = mainDisplayJson?.graphDetails?.filter(graph => graph.TabId === activeTab);
   const firstItem = filteredGraphs?.[0];
   const restItems = filteredGraphs?.slice(1);
   const graphDetails = mainDisplayJson?.graphDetails || [];
   const [visitedStoreData1, setVisitedStoreData] = useState([]);
   const [searchQuery, setSearchQuery] = useState('');

   // 🧠 Initialize tabCache state at the top of your component
   const [tabCache, setTabCache] = useState({});
   const isFocused = useIsFocused();

   let user_exist_data = useSelector(state => state?.user);
   const userId = user_exist_data.UserId || '';

   const onClickLogout = () => {
      setLogoutModal(false);
      Alert.alert(
         'Alert',
         'Are you sure you want to log out?',
         [
            {
               text: 'Cancel',
               onPress: () => console.log('Cancel Pressed'),
               style: 'cancel',
            },
            {
               text: 'OK',
               onPress: async () => {
                  await AsyncStorage.removeItem('@Dabur_DNA_User'); // ✅ Clear AsyncStorage
                  navigation.reset({ index: 0, routes: [{ name: 'Login' }] })
               }
            },
         ],
         { cancelable: false }
      );
   };

   useEffect(() => {
      getFilterStateCity()
   }, []);

   useEffect(() => {
      setTabCache({}); // reset cache when filters change
   }, [month, year]);

   useEffect(() => {
      if (mainDisplayJson && storeData?.StoreId) {
         setTimeout(() => getTabData(mainDisplayJson), 0);
      }
   }, [mainDisplayJson, storeData]);


   useEffect(() => {
      getDataFromLocal();
   }, [isFocused])


   const insertStoreInfoDNALocal = (data_arr = []) => {
      const d2 = moment().format('MM/DD/YYYY');
      return new Promise((resolve, reject) => {
         if (!Array.isArray(data_arr) || data_arr.length === 0) {
            resolve(true);
            return;
         }
         const escape = str => (str || '').toString().replace(/'/g, "''");
         db.transaction(tx => {
            data_arr.forEach(item => {
               const { StoreId, StoreName, ChainName, Address, Pincode, StateName, StoreType, CityName } = item;
               tx.executeSql(
                  `SELECT * FROM StoreInfoDNALocal WHERE StoreId = ?`,
                  [StoreId],
                  (_, { rows }) => {
                     if (rows.length === 0) {
                        // StoreId does not exist, insert it
                        const sql = `
                                INSERT INTO StoreInfoDNALocal
                                (VISIT_DATE, StoreId, StoreName, ChainName, Address, Pincode, CityName, StateName, StoreType, UPLOAD_STATUS)
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
                        tx.executeSql(sql, [
                           d2,
                           StoreId,
                           escape(StoreName),
                           escape(ChainName),
                           escape(Address),
                           escape(Pincode),
                           escape(CityName),
                           escape(StateName),
                           escape(StoreType),
                           'P'
                        ]);
                     } else {
                        console.log(`StoreId ${StoreId} already exists. Skipping insert.`);
                     }
                  },
                  err => {
                     console.log('Error checking existing StoreId:', err);
                     reject(err);
                  }
               );
            });


            resolve(true);
         });
      });
   };

   const getDataFromLocal = async () => {
      const d2 = moment().format('MM/DD/YYYY');
      // select * from StoreInfoDNALocal WHERE VISIT_DATE='07/22/2025' ORDER by StoreId  UPLOAD_STATUS
      return new Promise((resolve, reject) => {
         db.transaction(tx => {
            tx.executeSql(
               `select * from StoreInfoDNALocal WHERE VISIT_DATE= ?  ORDER by UPLOAD_STATUS`,
               [d2],
               (tx, results) => {

                  console.log("results===", results);
                  const rows = [];
                  for (let i = 0; i < results.rows.length; i++) {
                     rows.push(results.rows.item(i));
                  }
                  // console.log("rows===", rows)
                  setVisitedStoreData(rows);
                  // console.log('Completed categories from table:', completed);
                  resolve();
               },
               (tx, error) => {
                  console.log('DB error loading completed:', error);
                  reject(error);
               }
            );
         });
      });
   };

   const getTabData = async (tabData) => {
      if (!storeData?.StoreId) return;

      // const tabKey = `${mainTabIndex}_${storeData?.StoreId}_${year}_${month}`;
      const tabKey = `${mainTabIndex}_${storeData?.StoreId}_${year}_${month}_${Date.now()}`;
      if (tabCache[tabKey]) {
         console.log("Using cached data for tab:", tabKey);
         setGraphApiData(tabCache[tabKey]);
         return;
      }
      console.log("📦 TabKey:", tabKey);
      setLoading(true);
      try {
         const params = {
            parameters: {
               projectid: 41654,
               year: year,
               monthno: month,
               storeid: storeData?.StoreId
            }
         };
         console.log("🔁 API Params:", params);

         const graphDetails = tabData?.graphDetails || [];
         const uniqueUrls = [...new Set(graphDetails.map(graph => graph.GraphUrl))];

         const apiCalls = uniqueUrls.map(async url => {
            const config = {
               method: 'post',
               url: url,
               headers: {
                  'X-API-Key': 'f7fa9b09-ced8-4862-8cb7-5e7599d90fa2',
                  'Content-Type': 'application/json'
               },
               data: params
            };
            return await fetchWithRetry(config);
         });

         const results = await Promise.all(apiCalls);
         console.log("📊 API Results:", results.map(r => r?.data));

         const dataMap = {};
         uniqueUrls.forEach((url, idx) => {
            const responseData = results[idx]?.data;
            if (!responseData || !responseData.data || responseData.data.length === 0) {
               console.warn(`⚠️ API ${url} returned empty or invalid data`);
               // Optional: Retry or show error
            }
            dataMap[url] = responseData;
         });
         setGraphApiData(dataMap);
         setTabCache(prev => ({ ...prev, [tabKey]: dataMap }));

      } catch (err) {
         console.log("\u274C Error fetching tab data:", err);
      } finally {
         setLoading(false);
      }
   };

   const fetchWithRetry = async (config, retries = 2, delay = 1000) => {
      for (let i = 0; i <= retries; i++) {
         try {
            const res = await axios.request(config);
            if (res?.data?.status === 'success' && res?.data?.data) {
               return res;
            } else {
               console.warn(`Attempt ${i + 1} failed:`, res?.data?.error || 'No data');
            }
         } catch (err) {
            console.warn(`Attempt ${i + 1} failed with error:`, err.message);
         }
         if (i < retries) await new Promise(res => setTimeout(res, delay));
      }
      return null; // all attempts failed
   };

   const fetchDetailGraphs = async (detailPages) => {
      try {
         const resultMap = {};

         for (let item of detailPages) {
            const response = await post(item.GraphUrl, {
               parameters: {
                  projectid: 41654,
                  year: year,
                  monthno: month,
                  storeid: storeData?.StoreId
               },
            });
            console.log(`Data for ${item.GraphTitle}:`, response?.data); // Add this
            resultMap[item.GraphUrl] = response?.data || [];
         }
         setModalGraphData(resultMap);
      } catch (error) {
         console.log("❌ Error fetching detail graphs:", error);
      }
   };

   const handleScroll = (event) => {
      const offsetY = event.nativeEvent.contentOffset.y;
      setShowButton(offsetY > 0); // Show button only if not at the top
   };

   const openBottomSheet = () => {
      refRBSheet.current.open()
   }

   const onSelectStore = async (item) => {
      await insertStoreInfoDNALocal([item]);
      getDataFromLocal();
      setStoreData(item)
      setIsStoreSelected(true)
      // update mainDisplayJson as per currently selected tab
      const currentTab = mainTabs[mainTabIndex];
      setMainDisplayJson(currentTab?.MainTabData);

      getTabData(currentTab?.MainTabData);
      refRBSheet.current.close()
   }

   const onSelectSubTab = (item) => {
      setActiveTab(item?.TabId)
   }

   const getFilterStateCity = async () => {
      try {
         const params = JSON.stringify({ "UserId": userId || '' });

         const config = {
            method: 'post',
            url: ApiURL.storeDNAfilter,
            headers: {
               'api_key': '9a1f056fecb84eaf8eb4152dda22ab0501955c4f9bbe7daa8780740459fdde7a',
               'Content-Type': 'application/json'
            },
            data: params
         };

         const response = await axios.request(config);
         const resData = response.data?.StoreDNAfilter || [];

         // Set all response data
         setFilterData(resData);

         // Set distinct state list
         const uniqueStates = Array.from(
            new Map(resData.map(item => [item.StateId, {
               label: item.StateName,
               value: item.StateId
            }])).values()
         );

         setStateOptions(uniqueStates);

      } catch (error) {
         console.log("❌ Filter API error:", error);
      }
   };

   const storeSearchApi = async () => {
      console.log('state--', state, city);
      console.log('searchText--', searchText);

      // setSearchResult(!searchResult)
      setLoading(true)
      try {
         const params = JSON.stringify({
            "StateId": state ? state : "0",
            "CityId": city ? city : "0",
            "AsmAreaId": asmArea ? asmArea : "0",
            "StoreSearchText": searchText ? searchText : "",
            "UserId": userId || 0,
         });
         console.log('params---->', params);



         const config = {
            method: 'post',
            url: ApiURL.storeSearch,
            headers: {
               'api_key': '9a1f056fecb84eaf8eb4152dda22ab0501955c4f9bbe7daa8780740459fdde7a',
               'Content-Type': 'application/json'
            },
            data: params
         };

         const response = await axios.request(config);
         const resData = response.data?.StoreDNAstoreSearch || [];
         setStoreList(resData)
         setLoading(false)

         console.log('storeSearchApi====>', JSON.stringify(resData));

      } catch (error) {
         setLoading(false)
         console.log("❌ Filter API error:", error);
      }
   };

   const renderItem = ({ item }) => {
      const apiData = graphApiData[item.GraphUrl];
      // const values = apiData?.data || [];
      const values = apiData?.data?.length ? apiData.data : [];

      const scoreValue = values.length > 0 ? Object.values(values[0])[0] : null;
      // <Text>{scoreValue !== undefined ? `${scoreValue.toFixed(1)}%` : "No Data"}</Text>

      if (apiData?.status === 'error') {
         return (
            <View style={styles.percentBox}>
               <Text style={styles.boxText}>{item.GraphTitle}</Text>
               <Text style={styles.boxText}>❌</Text>
            </View>
         );
      }

      switch (item.GraphType) {
         case "ScoreCard":
            const firstDataObj = values[0] || {};
            const scoreValue = Object.values(firstDataObj)[0]; // dynamically get first value
            // const scoreValue = values.length > 0 ? Object.values(values[0])[0] : null;
            return (
               <View style={[styles.percentBox, { backgroundColor: item.GraphBackground }]}>
                  <Text style={styles.boxText}>{item.GraphTitle}</Text>
                  <Text style={[styles.boxText, { fontWeight: '500', fontSize: 24, marginTop: 10 }]}>
                     {scoreValue !== undefined ? `${scoreValue.toFixed(1)}%` : "0.0"}
                  </Text>
               </View>
            );

         //GIFTED CHART LIBRARY -----
         case "BarGraph":
            const chartWidth = screenWidth * 0.80;
            const barWidth = 40;
            const barColors = ['#1BF2E0', '#1B7BF2', '#1BC0F2'];

            const barData = values.map((v, idx) => {
               const value = parseFloat(Object.values(v).find(val => typeof val === 'number').toFixed(1));
               return {
                  value,
                  label: v.CalendarYear_Month,
                  frontColor: barColors[idx % barColors.length],
                  topLabelComponent: () => (
                     <Text style={{ color: '#000', fontSize: 12, fontWeight: '500', marginBottom: 5 }}>{value}%</Text>
                  )
               };
            });

            const visibleBars = barData.length;
            const totalSpacing = chartWidth - visibleBars * barWidth;
            const spacing = totalSpacing / (visibleBars + 1);

            if (!values || values == '' || values == undefined || values == null) {
               return null;
            }

            return (
               <View style={{ width: '100%', alignItems: 'center', justifyContent: 'center', padding: 10, borderWidth: 0.5, borderRadius: 25, }}>
                  {/* <View style={{ alignSelf: 'center', borderWidth: 0.5,borderRadius:20, paddingBottom: 10 }}> */}
                  <Text style={{ color: '#000', fontSize: 16, fontWeight: '600', marginBottom: 10 }}>
                     {item.GraphTitle}
                  </Text>

                  <BarChart
                     data={barData}
                     barWidth={barWidth}
                     spacing={spacing}
                     noOfSections={6}
                     maxValue={105}
                     roundedTop={false}
                     disableScroll={true}
                     yAxisLabelTexts={['0%', '20%', '40%', '60%', '80%', '100%']}
                     // yAxisLabelTexts={['0%', '👉', '👉', '👉', '👉', '100%']} // 👈 only 0% and 100%
                     yAxisTextStyle={{ color: '#000', fontSize: 12 }}
                     xAxisLabelTextStyle={{ color: '#000', fontSize: 12, fontWeight: '500', marginTop: 5 }}
                     isAnimated
                     width={chartWidth}
                     hideYAxisText={true} //to hide y axis text
                     // hideRules={true}
                     hideYAxisLine={true}
                     yAxisThickness={0}
                     xAxisThickness={0}
                     rulesLength={chartWidth}
                     // xAxisLength={chartWidth}
                     hideAxesAndRules={false}
                  // xAxisLabelTextStyle={{ color: '#000', fontSize: 10, marginTop: 4 }}
                  />
                  {/* </View> */}
                  <View style={{ height: 10, }} />
               </View>
            );

         case "Table":
            return (
               <View style={{ flex: 1 }}>
                  <ScrollView>
                     <Text style={{ color: '#000', fontSize: 16, fontWeight: '600', marginBottom: 10 }}>{item.GraphTitle}</Text>
                     {values.map((row, index) => {
                        const keys = Object.keys(row);
                        return (
                           <View key={index} style={{
                              flexDirection: 'row',
                              justifyContent: 'space-between',
                              paddingVertical: 8,
                              borderBottomWidth: 1,
                              borderColor: '#ddd'
                           }}>
                              <Text style={{ width: '50%', color: '#000' }}>{row[keys[0]]}</Text>
                              <Text style={{ width: '50%', color: '#000' }}>{row[keys[1]]}</Text>
                           </View>
                        )
                     })}
                     <View style={{ marginBottom: 80 }} />
                  </ScrollView>
               </View>
            );

         case "PieChart":
            const pieChartData = values.map((item, idx) => {
               const [labelKey, valueKey] = Object.keys(item);
               return {
                  name: item[labelKey],
                  population: item[valueKey],
                  color: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF'][idx % 5],
                  legendFontColor: "#7F7F7F",
                  legendFontSize: 12
               };
            });

            return (
               <View style={{ flex: 1 }}>
                  <PieChart
                     data={pieChartData}
                     width={screenWidth}
                     height={220}
                     chartConfig={{
                        backgroundColor: '#ffffff',
                        backgroundGradientFrom: '#ffffff',
                        backgroundGradientTo: '#ffffff',
                        fillShadowGradientFrom: '#BFC2FF',
                        fillShadowGradientTo: '#BFC2FF',
                        fillShadowGradientFromOpacity: 1,
                        fillShadowGradientToOpacity: 1,
                        decimalPlaces: 0,
                        color: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
                        labelColor: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
                        barPercentage: 1,
                        propsForBackgroundLines: {
                           stroke: 'transparent',
                        }
                     }}
                     accessor={"population"}
                     backgroundColor={"transparent"}
                     paddingLeft={"15"}
                     center={[10, 50]}
                     absolute
                  />
               </View>
            );

         default:
            return (
               null
            );
      }
   };


   // 🔧 Debounced search text handler (use lodash.debounce or implement custom debounce)
   const debouncedSearch = useCallback(_.debounce((text) => {
      setSearchText(text);
   }, 300), []);

   const feedbackCount = visitedStoreData1?.filter(item => item?.UPLOAD_STATUS == 'U')?.length;
   const filteredStores = storeList.filter((store) => {
      const query = searchQuery.toLowerCase();
      return (
         store.StoreName.toLowerCase().includes(query) ||
         store.StoreId.toString().includes(query)
      );
   });

   return (
      <SafeAreaView style={{ flex: 1, backgroundColor: GlobalTheme.colors.primary }}>
         <View style={{ flex: 1, backgroundColor: '#fff' }}>

            {/* MAIN DASHBOARD */}
            {!isStoreSelected ? (
               <View style={{ flex: 1 }} >
                  <View style={styles.headerStyle}>
                     <View style={{ paddingHorizontal: 15 }} />
                     <View style={{}}>
                        <Text style={styles.headerText}>{"Dashboard"}</Text>
                     </View>
                     <TouchableOpacity onPress={() => setLogoutModal(true)} style={styles.headerDotBtn}>
                        <Image source={IMAGES.dotsIcon} style={{ tintColor: '#fff', height: 27, width: 30, resizeMode: 'contain' }} />
                     </TouchableOpacity>
                  </View>

                  <TouchableOpacity onPress={() => openBottomSheet()} activeOpacity={0.8} style={styles.selectCard}>
                     <Image source={IMAGES.reportIcon} style={styles.iconStyle} />
                     <Text style={styles.storeText}> Select Store:</Text>
                     <Image source={IMAGES.downIcon} style={{ height: 20, width: 20, resizeMode: 'contain' }} />
                  </TouchableOpacity>
                  <Text style={styles.selectStoreText}>Select a store to view it's data.</Text>

                  <LinearGradient
                     colors={['#D8E7FF', '#FFFFFF',]}
                     start={{ x: 0, y: 0 }}
                     end={{ x: 1, y: 1 }}
                     style={styles.storeGredient}>

                     <View style={styles.todayStoreCard}>

                        <View style={{ marginLeft: 5, flexDirection: 'row', padding: 10, alignItems: 'center' }}>
                           <View style={{ backgroundColor: '#E3EBF8', padding: 5, borderRadius: 7 }}>
                              <Image source={IMAGES.storeIcon} style={{ height: 18, width: 18 }} />
                           </View>
                           <Text style={styles.todayStoreText}>Today's store</Text>
                        </View>
                        <View style={{ borderBottomWidth: 1.5, borderColor: '#E3EBF8' }} />

                        <View style={[styles.row, { paddingHorizontal: 10 }]}>
                           <View style={{ width: '48%', alignItems: 'center' }}>
                              <Text style={{ color: '#000', fontSize: 20, fontWeight: 'bold' }}>{visitedStoreData1 ? visitedStoreData1?.length : 0}</Text>
                              <Text style={{ color: '#808CA3', fontSize: 15, fontWeight: '400' }}>View</Text>
                           </View>
                           <View style={{ borderWidth: 1, height: 50, borderColor: '#E3EBF8' }} />
                           <View style={{ width: '48%', alignItems: 'center' }}>
                              <Text style={{ color: '#000', fontSize: 20, fontWeight: 'bold', textAlign: 'right' }}>{feedbackCount ? feedbackCount : 0}</Text>
                              <Text style={{ color: '#808CA3', fontSize: 15, fontWeight: '400', textAlign: 'right' }}>Feedback</Text>
                           </View>
                        </View>

                        <ScrollView showsVerticalScrollIndicator={false}>
                           <View style={{ marginTop: 5, marginHorizontal: 10 }}>
                              {visitedStoreData1 && visitedStoreData1?.map(store => (
                                 <TouchableOpacity
                                    disabled={store?.UPLOAD_STATUS == 'U' ? true : false}
                                    onPress={() => onSelectStore(store)}
                                    key={store.StoreId} style={styles.storeCard}>
                                    <View style={[styles.row, { margin: 0 }]}>
                                       <Text style={styles.cardTextBold}>{store.StoreName}</Text>
                                       {store?.UPLOAD_STATUS === 'U' ?
                                          <Image source={IMAGES.greenTick} style={{ height: 20, width: 20 }} />
                                          :
                                          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                             <View style={{ backgroundColor: '#FFF8CD', padding: 5, paddingHorizontal: 7, borderRadius: 15 }}>
                                                <Text style={{ color: 'orange', fontSize: 13, fontWeight: '500' }}>Pending</Text>
                                             </View>
                                             <Image source={IMAGES.rightArrowIcon} style={{ marginLeft: 10, height: 20, width: 20, resizeMode: 'contain', tintColor: '#97ADD6' }} />
                                          </View>
                                       }
                                    </View>
                                    <Text style={styles.cardText}>{store.Address}</Text>
                                 </TouchableOpacity>
                              ))}

                           </View>
                        </ScrollView>
                     </View>



                  </LinearGradient>
               </View>
            ) : (
               // STORE DASHBOARD
               <View style={styles.mainContainer}>
                  <CustomHeader
                     title="Store Dashboard"
                     leftIcon={IMAGES.backIcon}
                     onLeftPress={() => setIsStoreSelected(false)}
                     rightIcon={IMAGES.menuIcon}
                     onRightPress={() => setFeedBackModal(true)}

                  />
                  {/* Store Name Card */}
                  <View style={styles.row}>
                     <View style={styles.selectedStoreText}>
                        <View style={{ width: '88%' }}>
                           <Text style={[styles.storeNameText, {}]}>{storeData?.StoreName}</Text>
                           <Text style={{ color: GlobalTheme.colors.gray, fontSize: 13 }}>Store Id : {storeData?.StoreId}</Text>
                        </View>
                        <TouchableOpacity onPress={() => openBottomSheet()} style={styles.filterIcon}>
                           <Image source={IMAGES.filterIcon} style={{ height: 18, width: 18 }} />
                        </TouchableOpacity>
                     </View>
                     <TouchableOpacity onPress={() => navigation.navigate('StoreInfo', { storeData: storeData })} style={{ width: '25%', alignItems: 'flex-end' }}>
                        <Text style={styles.storeInfoText}>Store info</Text>
                     </TouchableOpacity>
                  </View>

                  {/* Year & Month Selector */}
                  <View style={{ flexDirection: 'row', alignItems: 'center', marginHorizontal: 10, marginTop: 5 }}>
                     <View style={{ width: 100, }}>
                        <CustomDropdown
                           data={yearData}
                           value={`${year}`}
                           placeholder='Year'
                           onChange={item => setYear(item.value)}
                           containerStyle={styles.yearDropDown}
                        />
                     </View>
                     <View style={{ width: 120, marginHorizontal: 10, }}>
                        <CustomDropdown
                           data={monthData}
                           value={`${month}`}
                           placeholder='Month'
                           onChange={item => setMonth(item.value)}
                           containerStyle={[styles.yearDropDown, { width: 120 }]}
                        />
                     </View>
                     <CustomButton title={'Show'}
                        style={styles.btnbg}
                        textstyle={styles.btntext}
                        onPress={() => {
                           if (storeData) {
                              console.log("🔽 Triggered getTabData with filters:", { year, month });
                              setTimeout(() => {
                                 getTabData(mainDisplayJson);
                              }, 50);
                           } else {
                              Alert.alert('Please select a store first.');
                           }
                        }}
                     />
                  </View>

                  <View style={styles.seperator} />

                  {/* Main Tab */}
                  <View style={{ flexDirection: 'row' }}>
                     {mainTabs.map((tab, index) => {
                        const isSelected = index === mainTabIndex;
                        return (
                           <TouchableOpacity
                              key={tab.MainTabId}
                              onPress={() => {
                                 setMainTabIndex(index);
                                 setMainDisplayJson(tab.MainTabData);  // update subTabs and graphDetails
                                 setActiveTab(tab.MainTabData.subTabs[0]?.TabId); // reset subTab on switch
                              }}
                              style={[
                                 styles.mtdTab,
                                 {
                                    borderBottomWidth: isSelected ? 3 : 0,
                                    backgroundColor: isSelected ? '#EFF6FF' : '#fff',
                                 }
                              ]} >
                              <Text
                                 style={[
                                    styles.mtdTabText,
                                    { color: isSelected ? '#113F8C' : '#000' }
                                 ]}
                              >
                                 {tab.MainTabName}
                              </Text>
                           </TouchableOpacity>
                        );
                     })}
                  </View>

                  {/* Sub Tab */}
                  <View style={styles.subTabView}>
                     <FlatList
                        data={mainDisplayJson?.subTabs}
                        horizontal
                        keyExtractor={(item) => item.TabId}
                        showsHorizontalScrollIndicator={false}
                        contentContainerStyle={{ paddingHorizontal: 10 }}
                        renderItem={({ item }) => {
                           const isSelected = activeTab === item.TabId;
                           return (
                              <TouchableOpacity onPress={() => onSelectSubTab(item)}
                                 style={[styles.subTab, { backgroundColor: isSelected ? '#113F8C' : '#fff' }]}>
                                 <Text style={[styles.tabText, { color: isSelected ? "#fff" : "#000" }]}>{item.TabName}</Text>
                              </TouchableOpacity>
                           )
                        }}
                     />
                  </View>

                  {/* Score Card */}
                  <View style={{ margin: 5 }}>
                     <View style={{ marginHorizontal: 5, marginTop: 5 }}>
                        {firstItem && (
                           <TouchableOpacity
                              activeOpacity={0.8}
                              onPress={() => {
                                 if (firstItem.clickable === 1 && firstItem.DetailsPage?.length > 0) {
                                    setSelectedDetails(firstItem.DetailsPage);
                                    setShowDetailsModal(true);
                                    fetchDetailGraphs(firstItem.DetailsPage);
                                 }
                              }}
                           >
                              <View style={{ width: '48%', height: 100, minHeight: 100, borderRadius: 20, justifyContent: 'center', alignItems: 'center', backgroundColor: "#C3D7FF", width: '100%', elevation: 0, }} >
                                 <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                    <View style={{ width: '80%', alignItems: 'center' }}>
                                       <Text style={styles.boxText}>{firstItem.GraphTitle}</Text>
                                       <Text
                                          style={[
                                             styles.boxText,
                                             { fontWeight: '500', fontSize: 24, marginTop: 10 },
                                          ]}
                                       >
                                          {(() => {
                                             const values = graphApiData[firstItem.GraphUrl]?.data || [];
                                             const score = Object.values(values[0] || {})[0];
                                             return score !== undefined ? `${score.toFixed(1)}%` : '0.0%';
                                          })()}
                                       </Text>
                                    </View>
                                    <View>
                                       {firstItem.clickable === 1 && (
                                          <Image source={IMAGES.rightArrowIcon} style={{ tintColor: '#000', height: 20, width: 20, resizeMode: 'contain' }} />
                                       )}
                                    </View>
                                 </View>
                              </View>
                           </TouchableOpacity>
                        )}
                     </View>
                     <View style={{ marginHorizontal: 10 }}>
                        <FlatList
                           data={restItems}
                           keyExtractor={(item, index) => `${item.GraphId}-${index}`}
                           renderItem={renderItem}
                           numColumns={2}
                           columnWrapperStyle={{ justifyContent: 'space-between', marginTop: 10 }}
                           contentContainerStyle={{ paddingHorizontal: 2, paddingVertical: 2 }}
                           showsVerticalScrollIndicator={false}
                        />
                     </View>
                  </View>
                  <Loader visible={loading} />

               </View>
            )}

            {/* Logout Pop-up Modal */}
            <Modal transparent visible={LogoutModal} animationType="fade" >
               <TouchableOpacity style={styles.modalOverlay} activeOpacity={0.1} onPress={() => setLogoutModal(false)}>
                  <View style={styles.modalContainer}>
                     <TouchableOpacity onPress={() => onClickLogout()} style={{ padding: 15 }}>
                        <Text style={{ color: '#000', fontSize: 14, fontWeight: '500' }}>Logout</Text>
                     </TouchableOpacity>

                  </View>
               </TouchableOpacity>
            </Modal>

            {/* Pop-up Modal */}
            <Modal transparent visible={FeedBackModal} animationType="fade" >
               <TouchableOpacity style={styles.modalOverlay} activeOpacity={0.1} onPress={() => setFeedBackModal(false)}>
                  <View style={styles.modalContainer}>
                     <TouchableOpacity onPress={() => { navigation.navigate('FeedbackCategories', { storeData: storeData }), setFeedBackModal(false) }} style={{ padding: 15 }}>
                        <Text style={{ color: '#000', fontSize: 14, fontWeight: '500' }}>Feedback and Rating</Text>
                     </TouchableOpacity>
                     <View style={{ borderBottomWidth: 1, borderColor: '#D8E3F1' }} />
                     <TouchableOpacity onPress={() => setFeedBackModal(false)} style={{ padding: 15 }}>
                        <Text style={{ color: '#000', fontSize: 14, fontWeight: '500' }}>Dashboard</Text>
                     </TouchableOpacity>
                  </View>
               </TouchableOpacity>
            </Modal>

            {/* Details Modal */}
            <Modal
               visible={showDetailsModal}
               animationType="slide"
               transparent={false}
               onRequestClose={() => {
                  setShowDetailsModal(false);
                  setModalGraphData({});
               }}>
               <View style={{ flex: 1, }}>
                  <View style={{ height: Platform.OS === 'ios' ? 50 : 0, backgroundColor: '#113F8C' }} />
                  <View style={{ width: '100%', backgroundColor: '#113F8C', borderBottomWidth: 1, borderColor: 'gray', padding: 5, paddingHorizontal: 20, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                     <View style={{ width: '93%', alignItems: 'center' }}>
                        <Text style={{ color: '#fff', fontSize: 20, fontWeight: 'bold', marginBottom: 10, alignSelf: 'center' }}>Details</Text>
                     </View>
                     <TouchableOpacity onPress={() => setShowDetailsModal(false)} style={{ width: '7%', alignItems: 'center' }}>
                        <Image source={IMAGES.crossIcon} style={{ height: 25, width: 25, resizeMode: 'contain' }} />
                     </TouchableOpacity>
                  </View>

                  <ScrollView style={{ padding: 20, backgroundColor: '#fff', }}>
                     {selectedDetails.map((detail, index) => {
                        const values = modalGraphData[detail.GraphUrl] || [];

                        if (!modalGraphData[detail.GraphUrl]) {
                           return (
                              <View key={index} style={{ marginBottom: 20 }}>
                                 <ActivityIndicator size="small" color="#113F8C" />
                              </View>
                           );
                        }

                        switch (detail.GraphType) {

                           case 'Table':
                              console.log('values details ->', JSON.stringify(values));

                              let displayKey = null;
                              let presentKey = null;
                              if (values.length > 0) {
                                 const presentKeys = Object.keys(values[0]).filter(k =>
                                    (typeof values[0][k] === 'string' && ['Yes', 'No'].includes(values[0][k])) ||
                                    typeof values[0][k] === 'boolean' ||
                                    typeof values[0][k] === 'number'
                                 );
                                 presentKey = presentKeys.length > 0 ? presentKeys[0] : null;
                                 const displayKeys = Object.keys(values[0]).filter(k => k !== presentKey && typeof values[0][k] === 'string');
                                 displayKey = displayKeys.length > 0 ? displayKeys[0] : null;
                              }

                              return (
                                 <View key={index} style={{ marginBottom: 30 }}>
                                    <Text style={{ color: '#000', fontSize: 16, fontWeight: '600', marginBottom: 10 }}>{detail.GraphTitle}</Text>

                                    {/* Header */}
                                    <View style={{
                                       flexDirection: 'row',
                                       justifyContent: 'space-between',
                                       backgroundColor: '#f5f5f5',
                                       paddingVertical: 8,
                                       paddingHorizontal: 10,
                                       borderTopLeftRadius: 8,
                                       borderTopRightRadius: 8,
                                    }}>
                                       <Text style={{ color: '#000', fontWeight: 'bold', width: '80%' }}>{displayKey ? displayKey.replace(/_/g, ' ').replace(/([a-z])([A-Z])/g, '$1 $2') : ''}</Text>
                                       <Text style={{ color: '#000', fontWeight: 'bold', width: '20%', textAlign: 'center' }}>{presentKey ? presentKey.replace(/_/g, ' ').replace(/([a-z])([A-Z])/g, '$1 $2') : ''}</Text>
                                    </View>

                                    <View style={{
                                       backgroundColor: '#fff',
                                       paddingHorizontal: 10,
                                       borderBottomLeftRadius: 8,
                                       borderBottomRightRadius: 8,
                                       shadowColor: '#000',
                                       shadowOffset: { width: 0, height: 1 },
                                       shadowOpacity: 0.1,
                                       shadowRadius: 2,
                                       elevation: 2
                                    }}>


                                       {values.map((row, idx) => {
                                          // Find the first key that could be a status (string "Yes"/"No", boolean, or number) as presentKey
                                          const presentKeys = Object.keys(row).filter(k =>
                                             (typeof row[k] === 'string' && ['Yes', 'No'].includes(row[k])) ||
                                             typeof row[k] === 'boolean' ||
                                             typeof row[k] === 'number'
                                          );
                                          const presentKey = presentKeys.length > 0 ? presentKeys[0] : null;
                                          // Find the first string key that is not presentKey as displayKey
                                          const displayKeys = Object.keys(row).filter(k => k !== presentKey && typeof row[k] === 'string');
                                          const displayKey = displayKeys.length > 0 ? displayKeys[0] : null;

                                          return (
                                             <View
                                                key={idx}
                                                style={{
                                                   flexDirection: 'row',
                                                   justifyContent: 'space-between',
                                                   paddingVertical: 8,
                                                   borderBottomWidth: idx === values.length - 1 ? 0 : 1,
                                                   borderColor: '#eee',
                                                }}>
                                                <Text style={{ color: '#000', width: '80%' }}>{row[displayKey] || '-'}</Text>
                                                <Text style={{ color: '#000', width: '20%', textAlign: 'center' }}>
                                                   {presentKey ? (
                                                      typeof row[presentKey] === 'string' && ['Yes', 'No'].includes(row[presentKey]) ? row[presentKey] :
                                                         typeof row[presentKey] === 'boolean' ? (row[presentKey] ? 'Yes' : 'No') :
                                                            typeof row[presentKey] === 'number' ? row[presentKey].toFixed(2) : row[presentKey] || '-'
                                                   ) : '-'}
                                                </Text>
                                             </View>
                                          );
                                       })}
                                    </View>
                                 </View>
                              );

                           default:
                              return (
                                 <View key={index} style={{ marginBottom: 20 }}>
                                    <Text>Unsupported GraphType: {detail.GraphType}</Text>
                                 </View>
                              );
                        }
                     })}

                  </ScrollView>


               </View>

            </Modal>

            {/* Bottom Sheet */}
            <RBSheet
               ref={refRBSheet}
               useNativeDriver={true}
               customStyles={{
                  wrapper: {
                     backgroundColor: 'rgba(0,0,0,0.2)',
                  },
                  container: {
                     height: '86%',
                     backgroundColor: '#fff',
                     borderTopLeftRadius: 20,
                     borderTopRightRadius: 20,
                     paddingBottom: 10,
                  },
                  draggableIcon: {
                     backgroundColor: 'gray',
                  },

               }}
               customModalProps={{
                  animationType: 'slide',
                  statusBarTranslucent: true,

               }}
               customAvoidingViewProps={{
                  enabled: false,
               }}>
               <View style={{ flex: 1, }}>
                  <View style={styles.header}>
                     <Text style={{ color: '#000', fontWeight: '500', fontSize: 16 }}>Select Store</Text>
                     <TouchableOpacity onPress={() => refRBSheet.current.close()}>
                        <Image source={IMAGES.crossIcon} style={styles.iconStyle} />
                     </TouchableOpacity>
                  </View>
                  <View style={{ marginVertical: 0, borderBottomWidth: 1, borderColor: '#ccc' }} />

                  <ScrollView showsVerticalScrollIndicator={false}
                     ref={scrollViewRef}
                     onScroll={handleScroll} >

                     <View style={{ flex: 1, margin: 15, }}>
                        <View style={[styles.row, {}]}>
                           <Text style={styles.dropHeaderText}>State</Text>
                           <Text style={styles.dropHeaderText}> City</Text>
                           {/* <Text style={styles.dropHeaderText}>  ASM Area</Text> */}
                        </View>

                        {/* Dropdown */}
                        {/* State city  static*/}
                        {/* <View style={{ marginTop: 5, flexDirection: 'row', alignItems: 'center' }}>
                                    <CustomDropdown
                                        data={data}
                                        value={state}
                                        onChange={item => setState(item.value)}
                                        containerStyle={{ flex: 1, }}
                                    />
                                    <CustomDropdown
                                        data={cityData}
                                        value={city}
                                        onChange={item => setCity(item.value)}
                                        containerStyle={{ flex: 1, marginHorizontal: 10 }}
                                    />
                                    <CustomDropdown
                                        data={cityData}
                                        value={asmArea}
                                        onChange={item => setAsmArea(item.value)}
                                        containerStyle={{ flex: 1, }}
                                    />
                                </View> */}

                        <View style={{ marginTop: 5, flexDirection: 'row', alignItems: 'center' }}>
                           {/* State Dropdown */}
                           <CustomDropdown
                              data={stateOptions}
                              value={state}
                              onChange={(item) => {
                                 setState(item.value);

                                 // Filter city options based on selected state
                                 const cities = filterData
                                    .filter(d => d.StateId === item.value)
                                    .map(d => ({
                                       label: d.CityName,
                                       value: d.CityId
                                    }));

                                 const asms = filterData
                                    .filter(d => d.StateId === item.value)
                                    .map(d => ({
                                       label: d.AsmAream,
                                       value: d.AsmAreaId
                                    }));

                                 // remove duplicates in city/asm
                                 const uniqueCities = Array.from(new Map(cities.map(c => [c.value, c])).values());
                                 const uniqueAsms = Array.from(new Map(asms.map(a => [a.value, a])).values());

                                 setCityOptions(uniqueCities);
                                 // setAsmOptions(uniqueAsms);
                                 setCity(null);     // reset
                                 // setAsmArea(null);  // reset
                              }}
                              containerStyle={{ flex: 1 }}
                           />

                           {/* City Dropdown */}
                           <CustomDropdown
                              data={cityOptions}
                              value={city}
                              onChange={(item) => setCity(item.value)}
                              containerStyle={{ flex: 1, marginHorizontal: 10 }}
                           />

                           {/* ASM Area Dropdown */}
                           {/* <CustomDropdown
                              data={asmOptions}
                              value={asmArea}
                              onChange={(item) => setAsmArea(item.value)}
                              containerStyle={{ flex: 1 }}
                           /> */}
                        </View>


                        <View style={[styles.searchBox, { marginTop: 20 }]}>
                           <Image source={IMAGES.searchIcon} style={{ height: 15, width: 15 }} />
                           <TextInput
                              style={styles.inputStyle}
                              placeholder='Search store...'
                              onChangeText={debouncedSearch}
                              placeholderTextColor={'gray'}
                           />

                        </View>

                        <View style={{ marginTop: 20 }}>
                           <CustomButton title={'Apply'} onPress={() => storeSearchApi()}
                              style={{ backgroundColor: GlobalTheme.colors.secondary, borderRadius: GlobalTheme.borderRadius.md }}
                              textstyle={{ color: GlobalTheme.colors.white, fontSize: GlobalTheme.typography.fontSize.medium }}
                           />
                        </View>

                        <View style={{ marginBottom: 70 }}>
                           <View style={{ marginTop: 20 }}>
                              {/* <Text style={{ color: '#000', fontSize: 14 }}>{storeList ? storeList.length : 0} Store</Text> */}
                              <Text style={{ color: '#000', fontSize: 14 }}>{filteredStores.length} Store{filteredStores.length !== 1 ? 's' : ''}</Text>
                           </View>

                           <View style={styles.searchByID}>
                              <Image source={IMAGES.searchIcon} style={{ height: 15, width: 15 }} />
                              <TextInput
                                 placeholder="Search by Store Name or Store ID"
                                 placeholderTextColor={'gray'}
                                 value={searchQuery}
                                 onChangeText={setSearchQuery}
                                 style={{ color: '#000', marginLeft: 5, height: 38, width: '95%' }}
                              />
                           </View>

                           {filteredStores && filteredStores.length > 0 ? filteredStores.map((store) => (
                              <TouchableOpacity onPress={() => onSelectStore(store)}
                                 key={store.StoreId} style={styles.storeCard}>
                                 <Text style={styles.cardTextBold}>{store.StoreName}</Text>
                                 <Text style={styles.cardText}>{store.Address}</Text>
                                 <Text style={styles.cardText}>{'Store Id:'} {store.StoreId}</Text>
                              </TouchableOpacity>
                           ))
                              : null
                           }


                        </View>



                     </View>



                  </ScrollView>
                  {showButton && (
                     <TouchableOpacity style={styles.floatingBtn} onPress={() => { scrollViewRef.current?.scrollTo({ y: 0, animated: true }) }}>
                        <Image source={IMAGES.upArrow} style={{ height: 15, width: 15 }} />
                     </TouchableOpacity>
                  )}
               </View>
               <Loader visible={loading} />
            </RBSheet>

         </View>
      </SafeAreaView>
   )
}

export default Dashboard
