'use client';
import { Layout } from '@/components/common/Layout';
import { PageLayout } from '@/components/common/PageLayout';
import { TabsNavigation } from '@/components/common/TabsNavigation';
import { DeploymentHistory } from '@/components/deployments/DeploymentHistory';
import { DeploymentOverview } from '@/components/deployments/DeploymentOverview';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { DeploymentForm } from '@/src/components/deployments/DeploymentForm';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { useVercelProject, VercelService } from '@/src/services/VercelService';
import { type DeploymentFormValues } from '@/types/deployment';
import { useSession } from 'next-auth/react';
import { useParams, useRouter } from 'next/navigation';
import { useState } from 'react';

export default function Page() {
  const { id } = useParams<{ id: string }>();
  const { data: session } = useSession();
  const router = useRouter();
  const { project, isLoading, error } = useVercelProject(id, session?.user?.vercelAccessToken);
  const { handle } = useApiWithToast();
  const [activeTab, setActiveTab] = useState('overview');

  const onSubmit = async (values: Partial<DeploymentFormValues>) => {
    await handle(VercelService.updateProject(id, values));
  };

  const tabs = [
    { value: 'overview', label: 'Overview' },
    { value: 'configuration', label: 'Configuration' },
    { value: 'deployments', label: 'Deployments' },
  ];

  return (
    <Layout>
      {isLoading && <Skeleton className='w-full h-full' />}
      {error && !isLoading && (
        <div className='flex flex-col items-center justify-center h-full gap-4 p-6'>
          <h2 className='text-xl font-semibold'>Error Loading Project</h2>
          <p className='text-neutral-400 text-center'>{error?.message ?? 'Project not found'}</p>
          <Button variant='light' onClick={() => router.push('/deployments')}>
            Back to Deployments
          </Button>
        </div>
      )}
      {!isLoading && !error && project && (
        <PageLayout title={project.name}>
          <Tabs defaultValue='overview' className='flex flex-col' value={activeTab} onValueChange={setActiveTab}>
            <TabsNavigation tabs={tabs} activeTab={activeTab} setActiveTab={setActiveTab} theme='dark' />

            <TabsContent value='overview'>
              <DeploymentOverview project={project} />
            </TabsContent>

            <TabsContent value='configuration'>
              <h3 className='text-xl mt-4 font-semibold mb-4 text-white'>Project configuration</h3>
              <DeploymentForm
                onSubmit={onSubmit}
                isDisabled={!project.id}
                isEdit={true}
                defaultValues={{
                  ...project,
                  ...(project.link &&
                    'repoId' in project.link && {
                      gitRepository: {
                        id: project.link.repoId ?? null,
                        type: project.link.type ?? 'github',
                        ref: project.link.productionBranch ?? 'main',
                        repo: project.link.repo ?? '',
                      },
                    }),
                }}
                isDeploying={false}
              />
            </TabsContent>

            <TabsContent value='deployments'>
              <DeploymentHistory project={project} />
            </TabsContent>
          </Tabs>
        </PageLayout>
      )}
    </Layout>
  );
}
