'use client';
import React from 'react';
import { cn } from '@/lib/utils';
import { PortfolioElement } from '@/src/types/portfolio';
import { ComponentControls } from '@/src/components/builder/common/ComponentControls';
import { components } from './componentRegistry';
import { useBuilder } from '../context/BuilderContext';
import { RenderComponentProps, RenderComponentOptions } from '@/src/types/builder';
import { usePathname } from 'next/navigation';

export function RenderComponent({
  element,
  options = {},
  setSectionContext,
  setShowSelector,
  isInSection = false,
}: RenderComponentProps) {
  const {
    onElementSelect,
    onElementRemove,
    onElementMove,
    selectedElementId,
    isPreview,
    portfolioProjects,
    onElementUpdate,
  } = useBuilder();
  const { controlsPosition = 'top-right', iconSize = 16, showControls = true, className } = options;
  const isSection = element.layout.startsWith('section_');
  const pathname = usePathname();
  const isBuilder = pathname.includes('/portfolios/') && !pathname.includes('/preview');

  const componentConfig = components[element.layout];

  const handlePropChange = (key: string, value: PortfolioElement['props'][string]) => {
    const newProps = {
      ...combinedProps,
      [key]: value,
    };
    onElementUpdate(element.id, newProps);
  };
  const { component: Component, defaultProps } = componentConfig;
  const isSelected = selectedElementId === element.id;
  if (element.layout === 'text') {
    element.props.isInSection = isInSection;
    element.props.onPropChange = handlePropChange;
  }

  const combinedProps = { id: element.id, ...defaultProps, ...element.props, projects: portfolioProjects || [] };

  if (isSection) {
    Object.assign(combinedProps, {
      onAddComponent: (position: string, top?: boolean) => {
        setSectionContext?.({ parentId: element.id, position, top });
        setShowSelector?.(true);
      },
    });
  }

  return (
    <div className='w-full'>
      <div
        key={element.id}
        className={cn(
          'mx-auto relative',
          isBuilder ? 'max-w-[1366px]' : '',
          !isPreview && [
            isSection ? 'group/section' : 'group/item',
            'border-2 border-transparent',
            isSelected ? 'border-2 ring-neutral-300' : '',
            'hover:border-neutral-400',
          ],
          className
        )}
      >
        {showControls && !isPreview && (
          <ComponentControls
            element={element}
            onElementSelect={onElementSelect}
            onElementRemove={onElementRemove}
            onElementMove={onElementMove}
            position={controlsPosition}
            iconSize={iconSize}
          />
        )}

        <Component {...combinedProps} />
      </div>
    </div>
  );
}

export function RenderComponents({
  elements,
  options = {},
  isInSection = false,
}: {
  elements: PortfolioElement[];
  options?: RenderComponentOptions;
  isInSection?: boolean;
}) {
  return (
    <>
      {elements.map((element) => (
        <RenderComponent key={element.id} element={element} options={options} isInSection={isInSection} />
      ))}
    </>
  );
}
