'use client';
import { PageLayout } from '@/components/common/PageLayout';
import { Layout } from '@/src/components/common/Layout';
import { ProjectForm } from '@/src/components/projects/ProjectForm';
import { ProjectFormSkeleton } from '@/src/components/skeletons/ProjectFormSkeleton';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { ProjectService, useProject } from '@/src/services/ProjectService';
import { Project, ProjectFormValues } from '@/src/types/project';
import { useParams, useRouter } from 'next/navigation';

export default function Page() {
  const { id } = useParams();
  const router = useRouter();
  const { project, isLoading, mutate } = useProject(id as string);
  const { handle } = useApiWithToast();

  const handleSubmit = async (data: ProjectFormValues) => {
    return await handle<Project>(ProjectService.updateProject(id as string, data), {
      mutate: () => mutate(),
      onSuccess: () => {
        router.back();
      }
    });
  };

  return (
    <Layout>
      <div className='flex flex-col h-full'>
        <PageLayout title='Edit Project'>
          {isLoading && <ProjectFormSkeleton />}
          {!isLoading && project && (
            <ProjectForm project={project} isEdit onSubmit={handleSubmit} cancelAction={() => router.back()} />
          )}
        </PageLayout>
      </div>
    </Layout>
  );
}
