import React, { useState, useRef, useEffect } from 'react';
import { View, Text, TouchableOpacity, ScrollView, FlatList } from 'react-native';
import { styles } from './style';
import { horizonalLine, Screen } from '../../../theme/theme';
import CustomHeader from '../../../components/CustomHeader';
import IMAGES from '../../../constants/Images';
import axios from 'axios';
import Loader from '../../../constants/Loader';

const storeinfodata = [
  {
    tabId: 0,
    section: 'Store details',
    items: [
      { brand: 'Store Name', name: 'Reliance Smart' },
      { brand: 'Store ID', name: '#98440' },
      { brand: 'Address', name: 'Rabindra Nagar, Delhi 110003' },
      { brand: 'City', name: 'Okhla' },
      { brand: 'Store Size', name: '1500–2000 sq ft' },
      { brand: 'Average Footfall', name: '10000' },
      { brand: 'Store age', name: '8' },
      { brand: 'Store Ranking', name: '24' },
    ],
  },
  {
    tabId: 0,
    section: 'Dabur Employees',
    items: [
      {  brand: 'RKAM', name: 'Rajesh Paal Singh' },
      { brand: 'SO', name: 'Soniya Singhal' },
    ],
  },
  {
    tabId: 0,
    section: '3P employees',
    items: [
      { brand: 'Promoter Name', name: 'Payal Singh' },
      { brand: 'AM Name', name: 'Soniya Singhal' },
      { brand: 'Supervisor Name', name: 'Soniya Dhankar' },
      { brand: 'City', name: 'Okhla' },
      { brand: 'Promoter duration', name: '2 Year 7 months' },
      { brand: 'Average incentive', name: '5000' },
    ],
  },

  // Last Visit Details (tabId: 1)
  {
    tabId: 1,
    section: 'Dabur employee',
    items: [
      { brand: 'SO', name: 'Rajesh Paal Singh', date: '23/05/2025', test: 'gxsjhxbas' },
      { brand: 'AH', name: 'Umesh Singh', date: '18/04/2025' },
      { brand: 'KAM', name: 'Rahul Tawde', date: '15/05/2025' },
      { brand: 'Others', name: 'Singhal Singh', date: '06/05/2025' },
    ],
  },
  {
    tabId: 1,
    section: '3P team',
    items: [
      { brand: 'Supervisor', name: 'Ashish Talwar', date: '27/05/2025' },
      { brand: 'AM', name: 'Soniya Singhal', date: '23/05/2025' },
    ],
  },

  // Competition (tabId: 2)
  {
    tabId: 2,
    section: 'Competition assets',
    items: [
      { brand: 'Marico', value: 5 },
      { brand: 'Colgate', value: 1 },
      { brand: 'Godrej', value: 2 },
      { brand: 'HUL', value: 1 },
      { brand: 'XX', value: 2 },
    ],
  },
  {
    tabId: 2,
    section: 'Promoter details',
    items: [
      { brand: 'Marico', value: 1 },
      { brand: 'Colgate', value: 1 },
      { brand: 'Godrej', value: 1 },
      { brand: 'HUL', value: 1 },
      { brand: 'XX', value: 0 },
    ],
  },
];



const tabs = [
  { id: 0, title: 'Store Info' },
  { id: 1, title: 'Last visit details' },
  { id: 2, title: 'Competition' },
];


const RenderHeader = ({ columns }) => {
  const colWidth = Screen.screenWidth * 0.95 / columns?.length;

  return (
    null
    // <View style={{ flexDirection: 'row', paddingVertical: 6 }}>
    //   {columns.map((col, index) => (
    //     <View key={index} style={{ width: colWidth }}>
    //       <Text style={styles.subheaderText}>{col.toUpperCase()}</Text>
    //     </View>
    //   ))}
    // </View>
  );
};


const RenderItem = ({ item, columns }) => {
  const colWidth = Screen.screenWidth * 0.95 / columns?.length;

  console.log('item------>',item);
  let col=item?.brand == 'Designation' ? [...columns[0]]:columns

  return (
    <View>
      <View style={styles.row}>
       
        {col.map((key, index) => (
          <View key={index} style={{ width: colWidth }}>
             {console.log("columns---",columns,"Designation",item)}
            <Text style={styles.name}>{item?.brand == 'Designation'? item?.name :String(item[key] ?? '')}</Text>
          </View>
        ))}
      </View>
      <View style={[horizonalLine, { marginVertical: 4 }]} />
    </View>
  );
};


const SectionListView = ({ listData }) => {
  const scrollRef = useRef(null); // shared horizontal scroll ref
console.log("/-",listData)
  return (
    <FlatList
      data={listData}
      keyExtractor={(item, index) => item.section + index}
      contentContainerStyle={{ paddingBottom: 20 }}
      ItemSeparatorComponent={() => <View style={{ paddingVertical: 5 }} />}
      renderItem={({ item }) => {
        const columns = Object.keys(item.items[0] || {}).filter(
          key => item.items.some(obj => obj[key] !== undefined && obj[key] !== null)
        );

        return (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>{item.section}</Text>
            <View style={[horizonalLine, { marginVertical: 10 }]} />

            {/* Shared horizontal scroll view for header + rows */}
            <ScrollView
              horizontal
              ref={scrollRef}
              showsHorizontalScrollIndicator={false}
              scrollEventThrottle={16}
            >
              <View>
                <RenderHeader columns={columns} />
                {item.items.map((subItem, index) => (
                  <RenderItem key={index} item={subItem} columns={columns} />
                ))}
              </View>
            </ScrollView>
          </View>
        );
      }}
    />
  );
};


const StoreInfo = ({ navigation, route }) => {

  const { storeData } = route.params || {};
  const [loading, setLoading] = useState(false)
  const [selectedTab, setSelectedTab] = useState(0);
  const [storeInfoData, setStoreInfoData] = useState([])


  useEffect(() => {
    getStoreInfo()
  }, [])

  // const getStoreInfo = async () => {
  //   setLoading(true)
  //   try {
  //     const params = { StoreId: storeData?.StoreId || "723" };
  //     const config = {
  //       method: 'post',
  //       url: 'https://api1.parinaam.in/api/dabur/StoreDNAstoreInfo',
  //       headers: {
  //         'api_key': '9a1f056fecb84eaf8eb4152dda22ab0501955c4f9bbe7daa8780740459fdde7a',
  //         'Content-Type': 'application/json'
  //       },
  //       data: params
  //     };

  //     const response = await axios.request(config);
  //     const res = response.data?.StoreDNAstoreInfo || {};

  //     // Flatten & transform API response into format usable by SectionListView
  //     const tempData = [];

  //     Object.entries(res).forEach(([sectionTitle, dataArray]) => {
  //       if (dataArray?.length > 0) {
  //         const tabId = dataArray[0]?.TabId ?? 0;

  //         // Convert single object to list of { key: value } pairs
  //         dataArray.forEach(item => {
  //           const cleanItem = { ...item };
  //           delete cleanItem.TabId;
  //           delete cleanItem.TabName;

  //           const formattedItems = Object.entries(cleanItem).map(([key, value]) => ({
  //             brand: key,
  //             name: String(value)
  //           }));

  //           tempData.push({
  //             tabId,
  //             section: sectionTitle.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase()),
  //             items: formattedItems
  //           });


            
  //         });
  //       }
  //     });
  //     setStoreInfoData(tempData);
  //     setLoading(false)
  //   } catch (error) {
  //     console.log("❌ store info api error:", error);
  //     setLoading(false)
  //   }
  // };

const getStoreInfo = async () => {
  setLoading(true);
  try {
    const params = { StoreId: storeData?.StoreId || "723" };
    const config = {
      method: 'post',
      url: 'https://api1.parinaam.in/api/dabur/StoreDNAstoreInfo',
      headers: {
        'api_key': '9a1f056fecb84eaf8eb4152dda22ab0501955c4f9bbe7daa8780740459fdde7a',
        'Content-Type': 'application/json'
      },
      data: params
    };

    const response = await axios.request(config);
    const res = response.data?.StoreDNAstoreInfo || {};

    // Step 1: Flatten API data
    const tempData = [];

    Object.entries(res).forEach(([sectionTitle, dataArray]) => {
      if (dataArray?.length > 0) {
        const tabId = dataArray[0]?.TabId ?? 0;
        let sec =sectionTitle.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
        dataArray.forEach(item => {
          const cleanItem = { ...item };
          delete cleanItem.TabId;
          delete cleanItem.TabName;

let formattedItems=[]
        if("Dabur Employee"==sec){
          console.log("tempData---14",item,sec)
        formattedItems = Object.entries(cleanItem).map(([key, value]) => ({
                    brand: key,
                    name: String(value)
                  }));
        }else{
          formattedItems = Object.entries(cleanItem).map(([key, value]) => ({
                    brand: key,
                    name: String(value)
                  }));
        }
          


          tempData.push({
            tabId,
            section: sec,
            items: formattedItems
          });
        });
      }
    });

    // Step 2: Group items by tabId and section
    const groupedData = {};

    tempData.forEach(entry => {
      const key = `${entry.tabId}-${entry.section}`;
      if (!groupedData[key]) {
        groupedData[key] = {
          tabId: entry.tabId,
          section: entry.section,
          items: []
        };
      } 
      groupedData[key].items.push(...entry.items);
    });

    // let objTemp={}
      // groupedData['0-Dabur Employee']?.items
      console.log("tempData-----gD",groupedData)
  
    // Step 3: Set to state
    setStoreInfoData(Object.values(groupedData));
    setLoading(false);
  } catch (error) {
    console.log("❌ store info api error:", error);
    setLoading(false);
  }
};



  const filteredData = Array.isArray(storeInfoData)
    ? storeInfoData.filter(item => item.tabId === selectedTab)
    : [];
  const selectedTabTitle = tabs?.find(tab => tab.id === selectedTab)?.title ?? 'NA';

  const dynamicTabs = Array.isArray(storeInfoData)
    ? Array.from(new Set(storeInfoData.map(item => item.tabId))).map(id => ({
      id,
      title: tabs.find(tab => tab.id === id)?.title || `Tab ${id}`
    }))
    : [];

    console.log("listData-----12",storeInfoData,filteredData)

  // const getStoreInfo = async () => {
  //   try {
  //     const params = {
  //       "StoreId": "723"
  //     };

  //     const config = {
  //       method: 'post',
  //       url: 'https://api1.parinaam.in/api/dabur/StoreDNAstoreInfo',
  //       headers: {
  //         'api_key': '9a1f056fecb84eaf8eb4152dda22ab0501955c4f9bbe7daa8780740459fdde7a',
  //         'Content-Type': 'application/json'
  //       },
  //       data: params
  //     };

  //     const response = await axios.request(config);
  //     const res = response.data?.StoreDNAstoreInfo || {};
  //     console.log('GET STORE INFO ==> ', JSON.stringify(res));

  //     const allItems = res && Object.values(res).flat(); // Flattened array
  //     setStoreInfoData(allItems);

  //     // Now extract TabId and TabName from array
  //     const tabData = allItems.map(item => ({
  //       TabId: item.TabId,
  //       TabName: item.TabName
  //     })).filter(item => item.TabId !== undefined && item.TabName);

  //     // Remove duplicates
  //     const uniqueTabs = Array.from(
  //       new Map(tabData.map(item => [`${item.TabId}-${item.TabName}`, item])).values()
  //     );

  //     console.log("tabData----", tabData, uniqueTabs)
  //     let NewObj = {}
  //     let ourVlue = uniqueTabs.map((item, i) => {
  //       NewObj[item?.TabName] = allItems?.filter((val) => val?.TabName == item?.TabName)
  //     })

  //     console.log("Unique Tabs:", uniqueTabs, JSON.stringify(NewObj));
  //     console.log("All Items:", JSON.stringify(allItems));

  //   } catch (error) {
  //     console.log("❌ store info api error:", error);
  //   }
  // };

  const renderTabContent = () => {
    switch (selectedTab) {
      case 0:
        return <SectionListView listData={filteredData} />
      case 1:
        return <SectionListView listData={filteredData} />
      case 2:
        return <SectionListView listData={filteredData} />;
      default:
        return null;
    }
  };

  return (
    <View style={[styles.container, { paddingHorizontal: 0 }]}>
      <CustomHeader
        title={'Store Info'}
        leftIcon={IMAGES.leftArrowIcon}
        onLeftPress={() => navigation.goBack()} />
      <View style={styles.container}>
        <View style={styles.tabstyle}>
          <ScrollView horizontal showsHorizontalScrollIndicator={false}>
            <View style={{ flexDirection: 'row' }}>
              {/* {tabs?.map((tab) => ( */}
              {dynamicTabs?.map((tab) => (
                <TouchableOpacity key={tab.id} style={styles.tabview} activeOpacity={1} onPress={() => setSelectedTab(tab.id)}>
                  <View style={selectedTab === tab.id ? styles.selecttabView : styles.unselecttabView}>
                    <Text style={[styles.tabtext, selectedTab === tab.id ? styles.selecttabText : styles.unselecttabText]}>
                      {tab.title}
                    </Text>
                  </View>
                </TouchableOpacity>
              ))}
            </View>
          </ScrollView>
        </View>
        <ScrollView horizontal={false} style={{ flex: 1 }}>
          <Text style={styles.headerText}>{selectedTabTitle} </Text>
          <View style={{ width: '100%' }}>{renderTabContent()}</View>
        </ScrollView>
      </View>
      <Loader visible={loading} />
    </View>
  );
};
export default StoreInfo;
