import clsx from 'clsx';
import React, { ReactNode, useEffect, useRef, useState } from 'react';
import { twMerge } from 'tailwind-merge';

interface Tab {
  label: string | ReactNode;
}

interface TabsProps {
  className?: string;
  tabs: Tab[];
  selectedIndex?: number;
  onTabClick?: (index: number) => void;
  textClass?: string;
}

const Tabs: React.FC<TabsProps> = (props) => {
  const { className, tabs, selectedIndex, onTabClick, textClass } = props;

  const scrollRef = useRef<HTMLDivElement>(null);
  const [isDragging, setIsDragging] = useState(false);
  const [startX, setStartX] = useState(0);
  const [scrollLeft, setScrollLeft] = useState(0);

  const handleTabClick = (index: number) => {
    if (onTabClick) {
      onTabClick(index);
    }
  };

  const handleTouchStart = (e: React.TouchEvent) => {
    if (tabs.length < 5) return;
    setIsDragging(true);
    setStartX(e.touches[0].pageX - (scrollRef.current?.offsetLeft || 0));
    setScrollLeft(scrollRef.current?.scrollLeft || 0);
  };

  const handleTouchMove = (e: React.TouchEvent) => {
    if (!isDragging || tabs.length < 5) return;
    e.preventDefault();
    const x = e.touches[0].pageX - (scrollRef.current?.offsetLeft || 0);
    const walk = (x - startX) * 2;
    if (scrollRef.current) {
      scrollRef.current.scrollLeft = scrollLeft - walk;
    }
  };

  const handleTouchEnd = () => {
    if (tabs.length < 5) return;
    setIsDragging(false);
  };

  useEffect(() => {
    if (tabs.length < 5) return;
    const tabsContainer = scrollRef.current;
    if (tabsContainer && selectedIndex !== undefined) {
      const selectedTab = tabsContainer.children[selectedIndex] as HTMLElement;
      if (selectedTab) {
        const containerWidth = tabsContainer.offsetWidth;
        const tabWidth = selectedTab.offsetWidth;
        const tabLeft = selectedTab.offsetLeft;
        const scrollLeft = tabLeft - (containerWidth - tabWidth) / 2;
        tabsContainer.scrollTo({ left: scrollLeft, behavior: 'smooth' });
      }
    }
  }, [selectedIndex, tabs.length]);

  const containerClassName = twMerge(
    tabs.length >= 5
      ? 'flex space-x-2 overflow-x-auto w-full scrollbar-hide'
      : 'flex space-x-2',
    className
  );

  return (
    <div
      ref={scrollRef}
      className={containerClassName}
      role='tablist'
      onTouchStart={handleTouchStart}
      onTouchMove={handleTouchMove}
      onTouchEnd={handleTouchEnd}
      style={
        tabs.length >= 5
          ? { WebkitOverflowScrolling: 'touch', paddingRight: '20px' }
          : undefined
      }
    >
      {tabs.map((tab, index) => (
        <button
          key={index}
          className={twMerge(
            clsx(
              'min-w-20 cursor-pointer rounded-md px-4 py-2 text-center font-sans font-medium',
              {
                'shrink-0': tabs.length >= 5,
                'text-base': !textClass,
                'bg-foreground-primary text-background-primary':
                  selectedIndex === index,
                'bg-background-tertiary text-foreground-primary hover:bg-foreground-primary/30':
                  selectedIndex !== index,
              }
            ),
            textClass
          )}
          onClick={() => handleTabClick(index)}
          role='tab'
          aria-selected={selectedIndex === index}
          aria-controls={`tabpanel-${index}`}
          id={`tab-${index}`}
        >
          <span className='line-clamp-1 break-all'>{tab.label}</span>
        </button>
      ))}
    </div>
  );
};

export default Tabs;
