"use client"

import React, { useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useAppDispatch, useAppSelector } from '@/lib/redux/hooks';
import { getBodySetting, getContentDetailSetting, getLayoutViewPage, getServicePath, getSidebarSetting, getTabSetting } from '@/lib/redux/features/serviceAdmin';
import { Select } from 'antd';
import { makeStyles } from 'tss-react/mui';
import { ArrowDownWideNarrow, ArrowUpNarrowWide } from 'lucide-react';
import { SortEntity } from '@/types/sort';
import useResponsive from '@/hooks/useResponsive';
import { useMounted } from '@/hooks/useMounted';
import StorageHelper from '@/lib/storeHelper';
import { STORAGE_KEYS } from '@/types/common';
import { BUTTON_ACTION, CONTENT_DETAIL_LAYOUT, LAYOUT_SETTING, TAB_TYPE } from '@/lib/appConstant';
import { getContentGroupByContentId, getFullTextSearchRequest, getIsLoadingHashtag, getSearchRequest, getShowFavorite, getSortOrder } from '@/lib/redux/features/content';
import { getAuthInfo, getIsAuthenticated } from '@/lib/redux/features/auth';
import { getIdTabActive, setIdTabActive, setIsFullTextSearch } from '@/lib/redux/features/search-page';
import SearchBox from './search-box';
import Tab from '@mui/material/Tab';
import Tabs from '@mui/material/Tabs';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import { SearchTabResponse } from '@/types/serviceAdmin';

type PropsType = {
    tabs: SearchTabResponse[],
    handleChangeSearchValues: any,
};


const SearchBoxForm = ({ tabs, handleChangeSearchValues }: PropsType) => {
    const t = useTranslations("");
    const mounted = useMounted();
    const { below768, getBelow768 } = useResponsive();
    const dispatch = useAppDispatch();
    const isLoggedIn = !!useAppSelector(getIsAuthenticated);
    const layoutViewPage = useAppSelector(getLayoutViewPage);
    const fulltextSearchRequest = useAppSelector(getFullTextSearchRequest);
    const { contentLayoutDetail } = useAppSelector(getContentDetailSetting);
    const tabSetting = useAppSelector(getTabSetting);

    const searchRequest = useAppSelector(getSearchRequest);
    const activeTab = useAppSelector(getIdTabActive);


    const styleButtonSearch = tabSetting.buttons ? tabSetting.buttons.filter(item => item.actionType === BUTTON_ACTION.SEARCH.id)[0] : {};

    const useStyle = makeStyles()(() => ({
        tabs: {
            '& .Mui-selected': {
                color: '#000 !important'
            },
            '& div.Mui-disabled': {
                opacity: 0.2
            }
        },
        homeContents: {
            width: layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id ? 'calc(100%)' : 'calc(100% - 200px)',
            flex: '1 0 auto',
            height: contentLayoutDetail === CONTENT_DETAIL_LAYOUT.LIST_SAME_GROUP ? 'fit-content' : ''
        },
        bold: {
            fontWeight: 700
        },
        searchTab: {
            '& label': {
                fontWeight: 700
            }
        },
        navItem: {
            border: '1px solid #d0d0d0',
            flex: '1 0 0px',
            borderRadius: '5px 5px 0 0 !important',
            marginLeft: 4,
            background: tabSetting.backgroundColorInactive || 'LightGray',
            borderColor: tabSetting.backgroundColorInactive || 'LightGray',
            fontWeight: 700,
            fontSize: tabSetting.fontSize || '1rem',
            textAlign: 'center',
            '&:first-of-type': {
                marginLeft: 0
            },
            '& .nav-link': {
                color: `${tabSetting.colorInactive || '#fff'}!important`
            }
        },
        activeNav: {
            border: 'none',
            background: tabSetting.backgroundColor || '#3d993a',
            '& .nav-link': {
                color: `${tabSetting.color || '#fff'}!important`
            }
        },
        navlink: {
            border: 'none!important',
            borderRadius: '0!important',
            backgroundColor: 'unset!important',
            color: '#fff!important'
        },
        tabContent: {
            border: '2px solid #d0d0d0',
            borderTop: 0,
            backgroundColor: '#fff',
            padding: '1rem'
        },
        totalResults: {
            fontSize: '1rem',
            marginBottom: '0.5rem'
        },
        hidden: {
            display: 'none'
        },
        sortIcon: {
            fontSize: '1.5rem',
            marginLeft: '0.5rem'
        },
        disabled: {
            opacity: 0.6,
            pointerEvents: 'none'
        }
    }));
    const { classes } = useStyle();

    useEffect(() => {
        if (tabs && tabs.length > 0 && !activeTab && activeTab !== 0) {
            handleChangeTab(tabs[0]) 
        }
    
    }, []);

    const handleChangeTab = (tab: SearchTabResponse) => {
        dispatch(setIdTabActive(tab.id));
        if (tab.type === TAB_TYPE.FULLTEXT_SEARCH.id) {
            // setIsSearchFullText(true);
            dispatch(setIsFullTextSearch(true));
        } else {
            // setIsSearchFullText(false);
            dispatch(setIsFullTextSearch(false));
        }
    };
    
    return (
        <div className={`${classes.searchTab}`}>
            {
                tabs.length > 1 &&
                <Tabs
                    style={{ borderBottom: 0, width: '100%' }}
                    className={classes.tabs}
                    value={activeTab || tabs[0].id}
                    variant="scrollable"
                    scrollButtons="auto"
                    allowScrollButtonsMobile
                    slots={{
                    startScrollButtonIcon: ({ ownerState }) => <LeftOutlined disabled={!!ownerState?.disabled}/>,
                    endScrollButtonIcon: ({ ownerState }) => <RightOutlined disabled={!!ownerState?.disabled}/>,
                    }}
                    indicatorColor="none"
                >
                    {
                        tabs.length > 0 && tabs.map(tab => {
                            return (
                                <Tab
                                    label={tab.title}
                                    className={`${classes.navItem} ${activeTab === tab.id && classes.activeNav} rounded-tl-[5]`}
                                    style={{ margin: '5px 2px 0 2px', cursor: 'pointer', padding: '2px 1px', minWidth: '150px' }}
                                    key={`nav-${tab.id}`}
                                    value={tab.id}
                                    onClick={() => handleChangeTab(tab)}
                                />
                            );
                        })
                    }
                </Tabs>
            }
            {/* <Nav tabs pills style={{ borderBottom: 0 }}>
                {
                    tabs.length > 0 && tabs.map((tab) => {
                        return (
                            <NavItem className={`${classes.navItem} ${activeTab === tab.id && classes.activeNav}`} style={{ margin: '5px 3px 0 3px' }} key={`nav-${tab.id}`}>
                                <NavLink
                                    className={`${classes.navlink}`}
                                    onClick={() => handleChangeTab(tab)}
                                    active={activeTab === tab.id}
                                    style={{ cursor: 'pointer' }}
                                >
                                    {tab.title}
                                </NavLink>
                            </NavItem>
                        );
                    })
                }
            </Nav> */}
            <div className={classes.tabContent}>
                {
                    tabs.length > 0 && tabs
                    .filter(tab => activeTab === tab.id)
                    .map(tab => {
                        return (
                            <div key={`pane-${tab.id}`}>
                                <SearchBox
                                    isLoggedIn={isLoggedIn}
                                    activeTab={activeTab}
                                    tabId={tab.id}
                                    searchBoxs={tab.searchBoxes}
                                    onSubmit={(searchValues: any, isSearchSpecialContentsGroup?: boolean) => handleChangeSearchValues(searchValues, tab, isSearchSpecialContentsGroup)}
                                    styleButtonSearch={styleButtonSearch}
                                    searchRequest={tab.type === TAB_TYPE.FULLTEXT_SEARCH.id ? fulltextSearchRequest : searchRequest}
                                />
                            </div>
                        );
                    })
                }
            </div>
        </div>
    );
};

export default  SearchBoxForm

