'use client';
import { PageLayout } from '@/components/common/PageLayout';
import { PortfolioForm } from '@/components/portfolios/PortfolioForm';
import { Layout } from '@/src/components/common/Layout';
import { PortfolioFormSkeleton } from '@/src/components/skeletons/PortfolioFormSkeleton';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { PortfolioService, usePortfolio } from '@/src/services/PortfolioService';
import { PortfolioFormValues } from '@/src/types/portfolio';
import { Portfolio } from '@prisma/client';
import { useParams } from 'next/navigation';

export default function Page() {
  const { handle } = useApiWithToast();
  const { id } = useParams();
  const { portfolio, isLoading, mutate } = usePortfolio(id as string);

  const handleSubmit = async (values: PortfolioFormValues) => {
    return await handle<Portfolio>(PortfolioService.updatePortfolio(id as string, values), {
      redirectTo: `/dashboard`,
      mutate: () => mutate(),
    });
  };

  return (
    <Layout>
      <PageLayout title='Edit Portfolio'>
        {isLoading && <PortfolioFormSkeleton />}
        {!isLoading && portfolio && <PortfolioForm onSubmit={handleSubmit} defaultValues={portfolio} isEdit={true} />}
      </PageLayout>
    </Layout>
  );
}
