'use client';
import { RenderComponent } from '@/src/components/builder/config/renderComponent';
import { BuilderProvider } from '@/src/components/builder/context/BuilderContext';
import PreviewNavbar from '@/src/components/preview/PreviewNavbar';
import { ViewportSimulator } from '@/src/components/preview/ViewportSimulator';
import { BuilderSkeleton } from '@/src/components/skeletons/BuilderSkeleton';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { useLastPortfolioRevision } from '@/src/services/PortfolioRevisionService';
import { PortfolioService, usePortfolio } from '@/src/services/PortfolioService';
import { PortfolioElement } from '@/src/types/portfolio';
import { useSession } from 'next-auth/react';
import { useParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import { ViewportType } from '@/src/types/preview';
import { VIEWPORT_CONFIGS } from '@/src/utils/viewport';
import { setGlobalTypography } from '@/src/lib/typography';
import { setGlobalColors } from '@/lib/theme';
import { usePortfolioProjects } from '@/src/services/PortfolioProjectService';
import { PortfolioProjectStatus } from '@prisma/client';

export default function Page() {
  const { id } = useParams();
  const { portfolio, isLoading: portfolioLoading, mutate } = usePortfolio(id as string);
  const { revision, isLoading: revisionLoading } = useLastPortfolioRevision(id as string);
  const { projects, isLoading: projectsLoading } = usePortfolioProjects(id as string);
  const [elements, setElements] = useState<PortfolioElement[]>([]);
  const [viewport, setViewport] = useState<ViewportType>('desktop');
  const { data: session } = useSession();
  const { handle } = useApiWithToast();
  const url = process.env.NEXT_PUBLIC_FRONTEND_URL + `/${session?.user?.username}/${portfolio?.title}`;

  useEffect(() => {
    if (revision?.config?.elements) {
      setElements(revision.config.elements);
    }
    if (revision?.config?.colors) {
      setGlobalColors(revision.config.colors);
    }
    if (revision?.config?.typography) {
      setGlobalTypography(revision.config.typography);
    }
  }, [revision]);

  const isLoading = portfolioLoading || revisionLoading || projectsLoading;

  if (isLoading) {
    return <BuilderSkeleton />;
  }

  return (
    <div className='min-h-screen flex flex-col'>
      <PreviewNavbar
        title={portfolio?.title ?? ''}
        viewport={viewport}
        setViewport={setViewport}
        onPublish={() =>
          handle(PortfolioService.publishPortfolio(id as string, !portfolio?.is_published), {
            messageOnSuccess: !portfolio?.is_published
              ? `Your portfolio has been published view it at ${url}`
              : `Your portfolio has been unpublished`,
            messageOnError: 'Failed to publish portfolio',
            mutate: () => mutate(),
          })
        }
        viewportOptions={VIEWPORT_CONFIGS}
        isPublished={portfolio?.is_published ?? false}
        isOwner={session?.user?.id === portfolio?.ownerId}
      />

      <div className='flex-1 flex justify-center items-center'>
        <BuilderProvider
          value={{
            isPreview: true,
            portfolioProjects: projects.filter((project) => project.status !== PortfolioProjectStatus.REJECTED),
          }}
        >
          <style>{`
            ::selection {
              background: var(--color-accent);
              color: var(--color-background);
            }
          `}</style>
          <ViewportSimulator viewportConfig={VIEWPORT_CONFIGS[viewport]}>
            {elements.length === 0 ? (
              <div className='flex flex-col items-center justify-center h-full'>
                <p className='text-sm text-muted-foreground text-center'>No elements found</p>
              </div>
            ) : (
              elements.map((element: PortfolioElement) => <RenderComponent element={element} key={element.id} />)
            )}
          </ViewportSimulator>
        </BuilderProvider>
      </div>
    </div>
  );
}
