'use client';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import Tabs from '@/components/Tabs';
import { Container } from '@/components/UI/Container';
import type { ITab } from '@/components/Tabs/Tabs';
import StatisticsLayout from '@/pagesComponents/Statistics/components/StatisticsLayout';
import { useDeterminateWidget } from '@/pagesComponents/Statistics/utils/useDeterminateWidget';
import MileageMain from './Main';
import MileageByTime from './MileageByTime';
import MileageMonthly from './MileageMonthly';

const tabs = [
  { title: 'Vehicle', key: 'vehicle' },
  { title: 'Company', key: 'company' },
  { title: 'Driver', key: 'driver' },
] as const;

const widgets = {
  '': {
    title: 'Суммарный пробег',
    component: <MileageMain />,
  },
  mileage_by_time: {
    title: 'Пробег День/Месяц отчет',
    component: <MileageByTime />,
  },
  mileage_monthly: {
    title: 'Ежемесячный пробег',
    component: <MileageMonthly />,
  },
};

type TabKeys = (typeof tabs)[number]['key'];

const Statistics = () => {
  const searchParams = useSearchParams();
  const [activeTab, setActiveTab] = useState<TabKeys>(
    (searchParams.get('activeTab') as TabKeys) || tabs[0].key,
  );
  const router = useRouter();
  const activeWidget = searchParams.get('widget') || '';
  const { widget } = useDeterminateWidget({ activeWidget, redirectLink: '/statistics', widgets });

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

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

  return (
    <div>
      <section className='pb-6 flex justify-center border-b-[1px] border-light_gray'>
        <Tabs tabs={tabs as unknown as ITab[]} onChange={handleTabChange} value={activeTab} />
      </section>

      <StatisticsLayout title={widget.title}>{widget.component}</StatisticsLayout>
    </div>
  );
};

export default Statistics;
