import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useEffect, useRef, useState } from 'react';
import { Separator } from '@/components/ui/separator';
import { TabsNavigationProps } from '@/types/common';
import { cn } from '@/lib/utils';

export function TabsNavigation({
  tabs,
  activeTab,
  setActiveTab,
  storageKey = 'activeTab',
  theme = 'light',
}: TabsNavigationProps) {
  const tabsRef = useRef<HTMLDivElement>(null);
  const [indicatorStyle, setIndicatorStyle] = useState({ width: 0, left: 0 });
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    if (storageKey) {
      const savedTab = localStorage.getItem(storageKey);
      if (savedTab) {
        setActiveTab(savedTab);
      }
    }
  }, [setActiveTab, storageKey]);

  useEffect(() => {
    if (mounted && storageKey) {
      localStorage.setItem(storageKey, activeTab);
    }
  }, [activeTab, mounted, storageKey]);

  useEffect(() => {
    if (tabsRef.current) {
      const activeButton = tabsRef.current.querySelector(`[data-state="active"]`);
      if (activeButton) {
        const rect = activeButton.getBoundingClientRect();
        const parentRect = tabsRef.current.getBoundingClientRect();
        setIndicatorStyle({
          width: rect.width,
          left: rect.left - parentRect.left,
        });
      }
    }
  }, [activeTab]);

  return (
    <Tabs value={activeTab} onValueChange={setActiveTab} className={'w-full flex flex-col'}>
      <TabsList
        className={cn(
          'flex flex-col bg-transparent text-neutral-800 items-start relative p-0',
          theme === 'light' ? 'text-neutral-800' : 'text-neutral-200'
        )}
      >
        <div className='flex flex-row lg:gap-8' ref={tabsRef}>
          {tabs.map(({ value, label }) => (
            <TabsTrigger
              key={value}
              value={value}
              className={cn(
                'data-[state=active]:bg-transparent data-[state=active]:text-neutral-800 text-md sm:text-lg lg:text-xl font-bold',
                theme === 'light' ? 'text-neutral-800' : 'text-neutral-200 data-[state=active]:text-neutral-200'
              )}
            >
              {label}
            </TabsTrigger>
          ))}
        </div>
        {mounted && (
          <div
            className={cn(
              'h-[1px] bg-neutral-800 transition-all duration-300 absolute bottom-0',
              theme === 'light' ? 'bg-neutral-800' : 'bg-neutral-200'
            )}
            style={{
              width: `${indicatorStyle.width}px`,
              left: `${indicatorStyle.left}px`,
            }}
          />
        )}
      </TabsList>
      <Separator
        className={cn('w-full !bg-neutral-700 !h-[0.25px]', theme === 'light' ? '!bg-neutral-800' : '!bg-neutral-200')}
      />
    </Tabs>
  );
}
