import React, { useState, useCallback, useEffect } from 'react';
import classnames from '../../utils/classnames';
import { HamburgerMenuIcon } from '@radix-ui/react-icons';

/// 顶部 Tab 切换组件
const TopTabs = ({ tabs, initTab, onChangeTab }) => {
  // 获取初始化的tab下标
  const initIndex = tabs.findIndex((tab) => tab.code === initTab);
  const [activeTab, setActiveTab] = useState(initIndex);
  const [tabPosX, setTabPosX] = useState(0);
  const [isShowTab, setIsShowTab] = useState(false);
  const [showMobileMenu, setShowMobileMenu] = useState(false);
  const [showDropdown, setShowDropdown] = useState(false);

  const handleTabClick = useCallback(
    (index) => {
      setActiveTab(index);
      onChangeTab && onChangeTab(index);
    },
    [onChangeTab],
  );

  // PC 最多显示 5 个 tab，超过 5 个的放到下拉菜单中
  const visibleTabs = tabs.slice(0, 5);
  const dropdownTabs = tabs.slice(5);

  /// 计算出初始高亮下标的位置
  useEffect(() => {
    if (activeTab === -1) {
      setActiveTab(0);
    }
    setIsShowTab(tabs.length > 1);
    if (tabs.length > 5) {
      if (activeTab > 5 - 1) {
        setTabPosX(((5 * 100 + 50) / (5 + 1)).toFixed(4) + '%');
      } else {
        setTabPosX(((activeTab * 100 + 50) / (5 + 1)).toFixed(4) + '%');
      }
    } else {
      setTabPosX(((activeTab * 100 + 50) / tabs.length).toFixed(4) + '%');
    }
    // setTabPosX(((activeTab * 100 + 50) / visibleTabs.length).toFixed(4) + '%');
  }, [activeTab, tabs, visibleTabs]);

  return (
    <div className='w-full md:w-auto md:mt-8 md:mb-4'>
      <div className='flex w-full'>
        {/* 桌面端Tabs导航 */}
        <div className=' flex-col hidden md:flex'>
          <div className='grid grid-flow-col auto-cols-fr'>
            {visibleTabs.map((tab, index) => {
              const tabClassName = classnames(
                'mx-2 px-4 py-1 whitespace-nowrap rounded-md cursor-pointer transition duration-150 ease-in-out',
                {
                  'text-blue-500': index === activeTab && isShowTab,
                  'hover:bg-gray-300': index !== activeTab,
                },
              );
              return (
                <div
                  key={index}
                  className={tabClassName}
                  onClick={() => handleTabClick(index)}>
                  <center>{tab.name}</center>
                </div>
              );
            })}
            {dropdownTabs.length > 0 && (
              <div className='mx-2 px-4 py-1 whitespace-nowrap rounded-md cursor-pointer transition duration-150 ease-in-out hover:bg-gray-300'>
                <center
                  className=''
                  onClick={() => setShowDropdown(!showDropdown)}>
                  更多
                </center>
                {showDropdown && (
                  <>
                    <div
                      className='fixed inset-0'
                      onClick={() => setShowDropdown(false)}></div>
                    <div className='relative pl-[50%]'>
                      <div className='absolute z-10 translate-x-[-50%] mt-5 w-auto py-2 bg-white border rounded-md shadow-lg overflow-hidden'>
                        {dropdownTabs.map((tab, index) => {
                          const tabClassName = classnames(
                            'px-4 py-1 whitespace-nowrap cursor-pointer',
                            {
                              'text-blue-500':
                                index + 5 === activeTab && isShowTab,
                              'hover:bg-gray-300': index + 5 !== activeTab,
                            },
                          );
                          return (
                            <div
                              key={index + 5}
                              className={tabClassName}
                              onClick={() => {
                                handleTabClick(index + 5);
                                setShowDropdown(false);
                              }}>
                              <center>{tab.name}</center>
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  </>
                )}
              </div>
            )}
          </div>
          <div>
            <div
              className={`w-10 h-1 bg-blue-500 translate-x-[-50%] duration-300 ${
                isShowTab ? '' : 'hidden'
              }`}
              style={{ marginLeft: tabPosX }}></div>
          </div>
        </div>
        {/* 移动端Tabs导航 */}
        <div className='md:hidden flex w-full justify-between items-center'>
          <div className='p-2 text-gray-600 text-2xl text-bold'>
            {isShowTab ? tabs[activeTab].name : ''}
          </div>
          <button
            className='mx-1 w-8 h-8 text-sm rounded border border-gray-400'
            onClick={() => setShowMobileMenu(!showMobileMenu)}>
            <center>
              <HamburgerMenuIcon className='text-gray-600' />
            </center>
          </button>
          {showMobileMenu && (
            <div
              className='fixed left-0 top-0 w-full h-full bg-black opacity-50 z-40'
              onClick={() => setShowMobileMenu(false)}></div>
          )}
          <div
            className={`absolute left-0 top-0 bg-white shadow-lg rounded-md rounded-t-none px-4 py-2 w-full z-50 transition-all duration-300 ease-in-out ${
              showMobileMenu
                ? 'transform translateY-0'
                : 'transform -translate-y-full'
            }`}>
            {tabs.map((tab, index) => {
              const isLastItem = index === tabs.length - 1;
              const tabClassName = classnames(
                "block mx-2 my-1 px-4 py-1 whitespace-nowrap cursor-pointer transition duration-150 ease-in-out after:content-[''] after:block after:w-full after:mt-3 after:h-[1px] after:bg-gray-300 after:duration-300 after:rounded",
                {
                  'text-blue-500': index === activeTab,
                  'hover:bg-gray-300': index !== activeTab,
                  'after:hidden': isLastItem,
                },
              );
              return (
                <div
                  key={index}
                  className={tabClassName}
                  onClick={() => {
                    handleTabClick(index);
                    setShowMobileMenu(false);
                  }}>
                  {tab.name}
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
};

export default TopTabs;
