'use client';
import { ReactNode, useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Tabs from '@/components/Tabs';
import { Container } from '@/components/UI/Container';
import FullWindowComponentContextProvider from '@/contexts/FullWindowComponentContext';
import { Select } from '@/components/UI/Select';
import { info, tabs } from './constants';
import { TodayData } from './TodayData';
import { DashboardData } from './DashboardData/DashboardData';
import { Desktop } from './Desktop';
import './graphicStyles.css';


export const Dashboard = () => {
  const [days, setDays] = useState('7')
  const searchParams = useSearchParams();
  const [activeTab, setActiveTab] = useState<keyof typeof info>(
    (searchParams.get('activeTab') as keyof typeof info) || tabs[0].key,
  );
  const router = useRouter();

  const handleTabChange = (key: string): void => {
    setActiveTab(key as keyof typeof info);
    router.push(`/?activeTab=${key}`);
  };

  useEffect(() => {
    if (!tabs.find((tab) => tab.key === activeTab)) {
      setActiveTab(tabs[0].key as 'desktop');
      router.push('/');
    }
  }, [activeTab, router]);

  const components: Record<keyof typeof info, ReactNode> = {
    dashboard: <DashboardData days={days} />,
    day_data: <TodayData days={days} />,
    desktop: <Desktop days={days} />,
  };

  return (
    <Container>
      <div className='flex items-center justify-between'>
        <Tabs
          tabs={tabs}
          onChange={handleTabChange}
          value={activeTab}
          classes={{
            tab: 'w-[240px] pb-4 border-b-[4px] rounded-sm [&_span]:text-[20px] [&_span]:leading-5',
          }}
        />

        <Select
          options={[
            {
              label: '7 Дней',
              value: '7'
            },
            {
              label: '30 Дней',
              value: '30'
            }
          ]}
          classes={{
            root: '!w-[120px]',
          }}
          value={days}
          onChange={(e) => setDays(e?.toString() || '7')}
        />
      </div>

      <FullWindowComponentContextProvider>
        {components[activeTab]}
      </FullWindowComponentContextProvider>
    </Container>
  );
};
