'use client';
import { DeploymentsTable } from '@/components/deployments/DeploymentsTable';
import { ProjectsTable } from '@/components/projects/ProjectsTable';
import { Separator } from '@/components/ui/separator';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import AdminDashboard from '@/src/components/admin/AdminDashboard';
import { Layout } from '@/src/components/common/Layout';
import { TabsNavigation } from '@/src/components/common/TabsNavigation';
import DeploymentsJoin from '@/src/components/deployments/DeploymentsJoin';
import { PortfoliosTable } from '@/src/components/portfolios/PortfoliosTable';
import { useSession } from 'next-auth/react';
import { useEffect, useState } from 'react';
import { TableSkeleton } from '@/src/components/skeletons/TableSkeleton';

export default function Page() {
  const [activeTab, setActiveTab] = useState('portfolios');
  const [isUpdatingSession, setIsUpdatingSession] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const { data: session, update } = useSession();

  const tabs = [
    { value: 'portfolios', label: 'Portfolios' },
    { value: 'projects', label: 'Projects' },
    ...(process.env.NODE_ENV === 'production' ? [{ value: 'deployments', label: 'Deployments' }] : []),
  ];

  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.search);
    if (!session?.user.vercelAccessToken && urlParams.get('oauth') === 'success') {
      (async () => {
        setIsUpdatingSession(true);
        try {
          await update({ ...session });
        } catch (error) {
          console.error('Error updating session:', error);
        } finally {
          setIsUpdatingSession(false);
        }
      })();
    }
    setIsLoading(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (session?.user.role === 'ADMIN') {
    return <AdminDashboard />;
  }

  const renderDeploymentsContent = () => {
    if (isLoading || isUpdatingSession) {
      return <TableSkeleton />;
    }
    if (!session?.user.vercelAccessToken) {
      return <DeploymentsJoin />;
    }
    return <DeploymentsTable />;
  };

  return (
    <Layout>
      <div className='z-50 flex flex-col gap-5 h-full p-2 lg:p-4'>
        <h1 className='text-2xl lg:text-4xl font-bold text-neutral-800'>Dashboard</h1>
        <Tabs defaultValue='portfolios' className='w-full flex flex-col' value={activeTab} onValueChange={setActiveTab}>
          <TabsNavigation tabs={tabs} activeTab={activeTab} setActiveTab={setActiveTab} storageKey='dashboard-tab' />
          <Separator className='w-full' />
          <TabsContent value='portfolios' className='mt-4 ml-0'>
            <PortfoliosTable />
          </TabsContent>
          <TabsContent value='projects' className='mt-4 ml-0'>
            <ProjectsTable />
          </TabsContent>
          {process.env.NODE_ENV === 'production' && (
            <TabsContent value='deployments' className='mt-4 ml-0'>
              {renderDeploymentsContent()}
            </TabsContent>
          )}
        </Tabs>
      </div>
    </Layout>
  );
}
