import { View, Text, StyleSheet, Image, TouchableOpacity, Dimensions, TextInput, ScrollView, FlatList, Button, Alert, Modal, TouchableWithoutFeedback, StatusBar } from 'react-native'
import React, { 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 displayData from './display.json'
import { BarChart, LineChart, PieChart } 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 mainDisplayJson from './mainDisplay.json'

const Dashboard = (props) => {

    const { navigation } = props;
    const screenHeight = Dimensions.get('screen').height;
    const screenWidth = Dimensions.get('screen').width;
    const refRBSheet = useRef();
    const [isStoreSelected, setIsStoreSelected] = useState(false)
    const [searchResult, setSearchResult] = useState(false)
    const [storeData, setStoreData] = useState({})
    const [mainTab, setMainTab] = useState('mtd')
    const [activeTab, setActiveTab] = useState(displayData?.subTabs?.[0]?.TabId || 1)
    const [state, setState] = useState(null);
    const [year, setYear] = useState(null)
    const [month, setMonth] = useState(null)
    const [city, setCity] = useState(null);
    const [asmArea, setAsmArea] = useState(null);
    const scrollViewRef = useRef(null);
    const [showButton, setShowButton] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);


    // Handle scroll event to show/hide button
    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 = (item) => {
        setStoreData(item)
        setIsStoreSelected(true)
        refRBSheet.current.close()
    }

    const data = [
        { label: 'Delhi', value: '1' },
        { label: 'Mumbai', value: '2' },
    ];
    const cityData = [
        { label: 'Okhla', value: '1' },
        { label: 'Kalkaji', value: '2' },
        { label: 'South Ex.', value: '3' },
    ];
    const storeJson = [
        {
            id: 1,
            name: "Banarasi & Sons",
            address: "G-8, Mahakavi Goswami Tulsidas Marg, Paraag Vihar, Press Colony, Hari Nagar, New Delhi, 110027",
            status: "pending"
        },
        {
            id: 2,
            name: "Gupta store & Sons",
            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"
        },
        {
            id: 4,
            name: "Mohan Mahalaxmi store",
            address: "G-8, Mahakavi Goswami Tulsidas Marg, Paraag Vihar, Press Colony, Hari Nagar, New Delhi, 110027",
            status: "completed"
        },
        {
            id: 5,
            name: "Chawla Store",
            address: "G-8, Mahakavi Goswami Tulsidas Marg, Paraag Vihar, Press Colony, Hari Nagar, New Delhi, 110027",
            status: "completed"
        },
        {
            id: 6,
            name: "Chawla Store",
            address: "G-8, Mahakavi Goswami Tulsidas Marg, Paraag Vihar, Press Colony, Hari Nagar, New Delhi, 110027",
            status: "completed"
        },
        {
            id: 7,
            name: "Chawla Store",
            address: "G-8, Mahakavi Goswami Tulsidas Marg, Paraag Vihar, Press Colony, Hari Nagar, New Delhi, 110027",
            status: "completed"
        },
        {
            id: 8,
            name: "Chawla Store",
            address: "G-8, Mahakavi Goswami Tulsidas Marg, Paraag Vihar, Press Colony, Hari Nagar, New Delhi, 110027",
            status: "completed"
        },
        {
            id: 9,
            name: "Chawla Store",
            address: "G-8, Mahakavi Goswami Tulsidas Marg, Paraag Vihar, Press Colony, Hari Nagar, New Delhi, 110027",
            status: "completed"
        },


    ];
    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"
        },
        {
            id: 4,
            name: "Bansal General store",
            address: "G-8, Mahakavi Goswami Tulsidas Marg, Paraag Vihar, Press Colony, Hari Nagar, New Delhi, 110027",
            status: "completed"
        },
        {
            id: 5,
            name: "Bansal General store",
            address: "G-8, Mahakavi Goswami Tulsidas Marg, Paraag Vihar, Press Colony, Hari Nagar, New Delhi, 110027",
            status: "completed"
        },
        {
            id: 6,
            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 chartConfig = {
        backgroundColor: '#ffffff',
        backgroundGradientFrom: '#ffffff',
        backgroundGradientTo: '#ffffff',
        fillShadowGradientFrom: '#FF8C61', // For bar colors
        fillShadowGradientTo: '#FF8C61',
        fillShadowGradientFromOpacity: 1,
        fillShadowGradientToOpacity: 1,
        decimalPlaces: 0,
        color: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`, // Text color
        labelColor: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
        // barPercentage: 0.5,
        barPercentage: 1,

    };

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

    const filteredGraphs = displayData?.graphDetails?.filter(graph => graph.TabId === activeTab);
    const firstItem = filteredGraphs?.[0];
    const restItems = filteredGraphs?.slice(1);

    const renderItem = ({ item }) => {
        switch (item.GraphType) {
            case "ScoreCard":
                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 }]}>{"45%"}</Text>
                    </View>
                );

            case "BarGraph":
                const barData = {
                    labels: ["Jan", "Feb", "Mar", "Apr"],
                    datasets: [{ data: [35, 45, 20, 55] }]
                };
                return (
                    <View style={{ padding: 10, backgroundColor: '', borderRadius: 8 }}>
                        <Text style={{ fontSize: 16, fontWeight: '600', marginBottom: 10 }}>
                            SOS Compliance Trend
                        </Text>
                        <BarChart
                            data={barData}
                            width={screenWidth - 40}
                            height={220}
                            yAxisSuffix="%"
                            chartConfig={chartConfig}
                            fromZero
                            showValuesOnTopOfBars
                            withInnerLines
                        />
                    </View>
                );

            case "Table":
                return (
                    <View style={{ flex: 1, }}>
                        <ScrollView>
                            <View style={{ flexDirection: 'row', borderWidth: 1, borderColor: '#EAEAEA', alignItems: 'center', alignSelf: 'flex-start', padding: 5, borderRadius: 15 }}>
                                <TouchableOpacity
                                    style={[styles.subTab, { backgroundColor: '#113F8C' }]}>
                                    <Text style={[styles.tabText, { color: "#fff" }]}>{'Asset'}</Text>
                                </TouchableOpacity>

                                <TouchableOpacity
                                    style={[styles.subTab, { backgroundColor: '#113F8C' }]}>
                                    <Text style={[styles.tabText, { color: "#fff" }]}>{'Asset Details'}</Text>
                                </TouchableOpacity>

                            </View>

                            {assetData && assetData.map((table, index) => (
                                <View key={index} style={{ marginTop: 10 }}>
                                    <Text style={{ fontSize: 16, color: '#000', fontWeight: '500' }}>{table.section}</Text>

                                    <View style={{ marginTop: 5, backgroundColor: '#fff', elevation: 5, padding: 10, borderRadius: 10 }}>
                                        <View style={{ flexDirection: 'row', borderBottomWidth: 1, borderColor: '#E0E0E0', paddingBottom: 7, }}>
                                            <Text style={{ width: '50%', color: '#676767', fontSize: 14 }}>Display</Text>
                                            <Text style={{ width: '50%', color: '#676767', fontSize: 14 }}>Present</Text>
                                        </View>
                                        {
                                            table && table.data.map((item) => (
                                                <View style={{ marginTop: 3, flexDirection: 'row', paddingBottom: 7, borderBottomWidth: 1, borderColor: '#E0E0E0', }}>
                                                    <Text style={{ width: '50%', color: '#000', fontSize: 14, }}>{item.display}</Text>
                                                    <Text style={{ width: '50%', color: '#000', fontSize: 14, }}>{item?.present}</Text>
                                                </View>
                                            ))}
                                    </View>
                                </View>

                            ))}
                            <View style={{ marginBottom: 500 }} />
                        </ScrollView>
                    </View>
                )

            case "LineChart":
                return (
                    <View style={{ flex: 1, }}>
                        <Text>Bezier Line Chart</Text>
                        <LineChart
                            data={{
                                labels: ["January", "February", "March", "April", "May", "June"],
                                datasets: [
                                    {
                                        data: [
                                            Math.random() * 100,
                                            Math.random() * 100,
                                            Math.random() * 100,
                                            Math.random() * 100,
                                            Math.random() * 100,
                                            Math.random() * 100
                                        ]
                                    }
                                ]
                            }}
                            width={Dimensions.get("window").width} // from react-native
                            height={220}
                            yAxisLabel="$"
                            yAxisSuffix="k"
                            yAxisInterval={1} // optional, defaults to 1
                            chartConfig={{
                                backgroundColor: "#e26a00",
                                backgroundGradientFrom: "lgray",
                                backgroundGradientTo: "lightblue",
                                decimalPlaces: 2, // optional, defaults to 2dp
                                color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
                                labelColor: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
                                style: {
                                    borderRadius: 16
                                },
                                propsForDots: {
                                    r: "6",
                                    strokeWidth: "2",
                                    stroke: "#ffa726"
                                }
                            }}
                            bezier
                            style={{
                                marginVertical: 8,
                                borderRadius: 16
                            }}
                        />
                    </View>
                )
            case "PieChart":
                return (
                    <View style={{ flex: 1, }}>
                        <PieChart
                            data={PieData}
                            width={screenWidth}
                            height={220}
                            chartConfig={chartConfig}
                            accessor={"population"}
                            backgroundColor={"transparent"}
                            paddingLeft={"15"}
                            center={[10, 50]}
                            absolute
                        />
                    </View>
                )

            default:
                return (
                    <View style={[styles.percentBox, { backgroundColor: "#f8d7da", padding: 10, marginVertical: 5 }]}>
                        <Text style={[styles.boxText, { color: "#721c24" }]}>
                            Unsupported Graph Type: {item.GraphType}
                        </Text>
                    </View>
                );
        }
    };

    // download data
    useEffect(() => {
        const init = async () => {
            await getData(); // <-- Only dynamic live data
        };
        init();

        getTabData()

    }, []);

    // Insert fallback mock data if empty
    const insertMasterSurveyQuestion = (data_arr = []) => {
        return new Promise((resolve, reject) => {
            if (!Array.isArray(data_arr) || data_arr.length === 0) {
                resolve(true);
                return;
            }

            const escape = str => (str || '').toString().replace(/'/g, "''");

            const values = data_arr.map(item => {
                const {
                    MenuId, SurveyId, SurveyName, CategoryId, Category, CategorySequence,
                    QuestionId, Question, QuestionType, QuestionImageAllow, QEnable,
                    LengthValidation, MinLength, MaxLength, OTP, DateRange, QuestionSequence,
                    AnswerId, Answer, ImageAllow1, ImageAllow2, Image1Mandatory, Image2Mandatory,
                    QuestionImageMandatory, EnableQuestion, DisableQuestion, AnswerSequence,
                    ShowCat, SubCategoryId, SubCategory, SubCategorySequence,
                    QuestionTypeNew, CalFormula, RefImage, QuestionRefImage
                } = item;

                return `(
        '${MenuId}', '${SurveyId}', '${escape(SurveyName)}', '${CategoryId}', '${escape(Category)}',
        '${CategorySequence}', '${QuestionId}', '${escape(Question)}', '${escape(QuestionType)}',
        '${QuestionImageAllow ? 1 : 0}', '${QEnable ? 1 : 0}', '${LengthValidation ? 1 : 0}',
        '${MinLength}', '${MaxLength}', '${OTP ? 1 : 0}', '${escape(DateRange)}',
        '${QuestionSequence}', '${AnswerId}', '${escape(Answer)}',
        '${ImageAllow1 ? 1 : 0}', '${ImageAllow2 ? 1 : 0}', '${Image1Mandatory ? 1 : 0}',
        '${Image2Mandatory ? 1 : 0}', '${QuestionImageMandatory ? 1 : 0}',
        '${escape(EnableQuestion)}', '${escape(DisableQuestion)}', '${AnswerSequence}',
        '${ShowCat ? 1 : 0}', '${SubCategoryId}', '${escape(SubCategory)}',
        '${SubCategorySequence}', '${escape(QuestionTypeNew)}', '${escape(CalFormula)}',
        '${escape(RefImage)}', '${escape(QuestionRefImage)}'
      )`;
            });

            const sql = `
      INSERT INTO FeedbackCategory (
        MenuId, SurveyId, SurveyName, CategoryId, Category, CategorySequence,
        QuestionId, Question, QuestionType, QuestionImageAllow, QEnable,
        LengthValidation, MinLength, MaxLength, OTP, DateRange, QuestionSequence,
        AnswerId, Answer, ImageAllow1, ImageAllow2, Image1Mandatory, Image2Mandatory,
        QuestionImageMandatory, EnableQuestion, DisableQuestion, AnswerSequence,
        ShowCat, SubCategoryId, SubCategory, SubCategorySequence,
        QuestionTypeNew, CalFormula, RefImage,QuestionRefImage
      ) VALUES ${values.join(',')}
    `;

            db.transaction(tx => {
                tx.executeSql(`DELETE FROM FeedbackCategory`, [], () => {
                    tx.executeSql(sql, [], () => {
                        console.log('FeedbackCategory inserted successfully');
                        resolve(true);
                    }, (err) => {
                        console.log('Insert error in FeedbackCategory:', err);
                        reject(err);
                    });
                }, (err) => {
                    console.log('Delete error before insert FeedbackCategory:', err);
                    reject(err);
                });
            });
        });
    };

    async function getData() {
        try {
            const data1 = {
                Downloadtype: "Master_SurveyQuestion",
                Param1: "",
                Param2: "",
                username: "testmer",
            };

            const url = "https://di1.parinaam.in/Webservice/GenericService.svc/DownloadJson";
            console.log("Downloading from:", url, data1);

            const res = await getDownloadJson(url, data1);
            console.log('Response:', res);

            if (res?.Master_SurveyQuestion?.length) {
                const data = res.Master_SurveyQuestion || [];
                console.log("Inserting downloaded data into FeedbackCategory...");
                const all = await getAllFromTable('FeedbackCategory');
                if (all?.length === 0) {
                    console.log("Table empty. Inserting fallback mock data...");
                    await insertMasterSurveyQuestion(data);
                } else {
                    console.log("FeedbackCategory table already has data.");
                }
            } else {
                console.log("No Master_SurveyQuestion data found in response");
            }
        } catch (err) {
            console.log("Dashboard feedback survey download error:", err);
        }
    }
    // end download data.

    const getTabData = () => {
        let params = {
            "parameters": {
                "projectid": 41654,
                "year": 2025,
                "monthno": 6,
                "storeid": 2702
            }
        }
        post(ApiURL.pssscoreApi, params)
            .then(res => {
                console.log('psscoreApi res==>', res);

            })
    }

    return (
        <SafeAreaView style={{ flex: 1, backgroundColor: GlobalTheme.colors.primary }}>
            <View style={{ flex: 1, backgroundColor: '#fff' }}>
                {!isStoreSelected ?
                    <CustomHeader
                        title="  Dashboard"
                        rightIcon={IMAGES.menuIcon}
                        onRightPress={() => setModalVisible(true)}
                    />
                    :
                    <CustomHeader
                        title="Dashboard"
                        leftIcon={IMAGES.backIcon}
                        onLeftPress={() => setIsStoreSelected(false)}
                        rightIcon={IMAGES.menuIcon}
                        onRightPress={() => setModalVisible(true)}

                    />
                }

                {/* MAIN DASHBOARD */}
                {!isStoreSelected ? (
                    <View style={{ flex: 1 }} >

                        <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' }}>1</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' }}>2</Text>
                                        <Text style={{ color: '#808CA3', fontSize: 15, fontWeight: '400', textAlign: 'right' }}>Feedback</Text>
                                    </View>
                                </View>

                                <ScrollView showsVerticalScrollIndicator={false}>
                                    <View style={{ marginTop: 5, marginHorizontal: 10 }}>
                                        {visitedStoreData && visitedStoreData.map(store => (
                                            <TouchableOpacity onPress={() => navigation.navigate("FeedbackCategories")}
                                                key={store.id} style={styles.storeCard}>
                                                <View style={[styles.row, { margin: 0 }]}>
                                                    <Text style={styles.cardTextBold}>{store.name}</Text>
                                                    {store?.status === 'completed' ?
                                                        <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}>
                        <View style={styles.row}>
                            <View style={styles.selectedStoreText}>
                                <Text style={styles.storeNameText}> {storeData?.name}</Text>
                                <TouchableOpacity onPress={() => openBottomSheet()} style={styles.filterIcon}>
                                    <Image source={IMAGES.filterIcon} style={{ height: 18, width: 18 }} />
                                </TouchableOpacity>
                            </View>
                            <TouchableOpacity onPress={() => navigation.navigate('StoreInfo')} 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}
                            />
                        </View>
                        <View style={styles.seperator} />

                        {/* Main Tab */}
                        <View style={{ flexDirection: 'row' }}>
                            <TouchableOpacity onPress={() => setMainTab('mtd')}
                                style={[styles.mtdTab, { borderBottomWidth: mainTab === 'mtd' ? 3 : 0, backgroundColor: mainTab === 'mtd' ? '#EFF6FF' : '#fff' }]} >
                                <Text style={[styles.mtdTabText, { color: mainTab === 'mtd' ? '#113F8C' : '#000', }]}>MTD</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => setMainTab('lastVisit')}
                                style={[styles.mtdTab, { borderBottomWidth: mainTab === 'lastVisit' ? 3 : 0, backgroundColor: mainTab === 'lastVisit' ? '#EFF6FF' : '#fff' }]} >
                                <Text style={[styles.mtdTabText, { color: mainTab === 'lastVisit' ? '#113F8C' : '#000' }]}>Last Visit</Text>
                            </TouchableOpacity>
                        </View>

                        {/* <View style={{ flexDirection: 'row' }}>

                            {mainDisplayJson && mainDisplayJson?.Tabs.map((item, index) => (
                                <TouchableOpacity onPress={() => setMainTab('mtd')}
                                    style={[styles.mtdTab, { borderBottomWidth: mainTab === 'mtd' ? 3 : 0, backgroundColor: mainTab === 'mtd' ? '#EFF6FF' : '#fff' }]} >
                                    <Text style={[styles.mtdTabText, { color: mainTab === 'mtd' ? '#113F8C' : '#000', }]}>MTD</Text>
                                </TouchableOpacity>
                            ))}

                        </View> */}



                        {/* Sub Tab */}
                        <View style={styles.subTabView}>
                            <FlatList
                                data={displayData?.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>

                        {/* Boxes */}
                        <View style={{ margin: 10 }}>
                            {/* First full-width item */}
                            {firstItem && (
                                <View style={[styles.percentBox, { backgroundColor: firstItem.GraphBackground, width: '100%', elevation: 0 },]}>
                                    <Text style={styles.boxText}>{firstItem.GraphTitle}</Text>
                                    <Text style={[styles.boxText, { fontWeight: '500', fontSize: 24, marginTop: 10 }]}>{"45%"}</Text>
                                </View>
                            )}

                            <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>
                )}

                {/* Pop-up Modal */}
                <Modal transparent visible={modalVisible} animationType="fade" >
                    <TouchableOpacity style={styles.modalOverlay} activeOpacity={0.1} onPress={() => setModalVisible(false)}>
                        <View style={styles.modalContainer}>
                            <TouchableOpacity onPress={() => { navigation.navigate('FeedbackCategories'), setModalVisible(false) }} style={{ padding: 15 }}>
                                <Text style={{}}>Feedback and Rating</Text>
                            </TouchableOpacity>
                            <View style={{ borderBottomWidth: 1, borderColor: '#D8E3F1' }} />
                            <TouchableOpacity onPress={() => setModalVisible(false)} style={{ padding: 15 }}>
                                <Text style={{}}>Dashboard</Text>
                            </TouchableOpacity>
                        </View>
                    </TouchableOpacity>
                </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 */}
                                <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={[styles.searchBox, { marginTop: 20 }]}>
                                    {/* <Image source={IMAGES.searchIcon} style={{ height: 15, width: 15 }} /> */}
                                    <TextInput
                                        style={styles.inputStyle}
                                        placeholder='Search store...'
                                    />
                                </View>

                                <View style={{ marginTop: 20 }}>
                                    <CustomButton title={'Apply'} onPress={() => setSearchResult(!searchResult)}
                                        style={{ backgroundColor: GlobalTheme.colors.secondary, borderRadius: GlobalTheme.borderRadius.md }}
                                        textstyle={{ color: GlobalTheme.colors.white, fontSize: GlobalTheme.typography.fontSize.medium }}
                                    />
                                </View>
                                {searchResult ?
                                    <View style={{ marginBottom: 70 }}>
                                        <View style={{ marginTop: 20 }}>
                                            <Text style={{ color: '#000', fontSize: 14 }}>11 Store</Text>
                                        </View>

                                        {storeJson && storeJson.map(store => (
                                            <TouchableOpacity onPress={() => onSelectStore(store)}
                                                key={store.id} style={styles.storeCard}>
                                                <Text style={styles.cardTextBold}>{store.name}</Text>
                                                <Text style={styles.cardText}>{store.address}</Text>
                                            </TouchableOpacity>

                                        ))}


                                    </View>
                                    : null
                                }



                            </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>

                </RBSheet>

            </View>
        </SafeAreaView>
    )
}

export default Dashboard

