'use client';
import { PageLayout } from '@/components/common/PageLayout';
import { Terminal } from '@/components/common/Terminal';
import { Layout } from '@/src/components/common/Layout';
import { DeploymentForm } from '@/src/components/deployments/DeploymentForm';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { VercelService } from '@/src/services/VercelService';
import { type DeploymentEvent, type DeploymentFormValues } from '@/types/deployment';
import { GetDeploymentResponseBody } from '@vercel/sdk/models/getdeploymentop.js';
import { GetProjectsProjects } from '@vercel/sdk/models/getprojectsop.js';
import { useEffect, useState } from 'react';

export default function Page() {
  const { handle } = useApiWithToast();
  const [isDeploying, setIsDeploying] = useState(false);
  const [deploymentLogs, setDeploymentLogs] = useState<DeploymentEvent[]>([
    {
      id: crypto.randomUUID(),
      date: new Date().getTime(),
      text: 'You will see the deployment logs here',
      type: 'stdout',
    },
  ]);
  const [deploymentId, setDeploymentId] = useState<string | null>(null);

  useEffect(() => {
    if (!deploymentId) {
      return;
    }
    setIsDeploying(true);
    VercelService.pollDeploymentEvents(deploymentId, { onUpdate: (events) => setDeploymentLogs(events) });
  }, [deploymentId]);

  const onSubmit = async (values: Partial<DeploymentFormValues>) => {
    setIsDeploying(true);
    setDeploymentLogs([
      {
        id: crypto.randomUUID(),
        date: new Date().getTime(),
        text: 'Creating deployment...',
        type: 'stdout',
      },
    ]);
    const response = await handle<{ project: GetProjectsProjects; deployment: GetDeploymentResponseBody }>(
      VercelService.createProject(values)
    );
    if (response) {
      setDeploymentId(response.deployment.id);
    }
    setIsDeploying(false);
  };

  return (
    <Layout>
      <PageLayout title='New Deployment'>
        <div className='flex flex-col gap-4'>
          <DeploymentForm onSubmit={onSubmit} isDeploying={isDeploying} isDisabled={false} />
          <Terminal logs={deploymentLogs} isActive={isDeploying} className='mt-4' />
        </div>
      </PageLayout>
    </Layout>
  );
}
