'use client';
import { cn } from '@/lib/utils';
import { AddComponentButton } from '@/src/components/builder/common/AddComponentButton';
import { PortfolioElement } from '@/src/types/portfolio';
import { RenderComponents } from '@/src/components/builder/config/renderComponent';
import { useBuilder } from '@/src/components/builder/context/BuilderContext';
import { ThreeColumnsProps } from '@/src/types/section';
import Wrapper from '@/src/components/common/Wrapper';

export function ThreeColumns({ className, children = [], onAddComponent, sectionId, styling }: ThreeColumnsProps) {
  const { isPreview } = useBuilder();
  const leftChildren = children.filter((child) => child.props?.position === 'left');
  const middleChildren = children.filter((child) => child.props?.position === 'middle');
  const rightChildren = children.filter((child) => child.props?.position === 'right');

  const renderColumn = (position: 'left' | 'middle' | 'right', elements: PortfolioElement[]) => (
    <div className='w-full lg:w-1/3 space-y-4 bg-[var(--color-background)] text-[var(--color-text)]'>
      {elements.length > 0 ? (
        <div className='relative'>
          <div className='absolute left-0 right-0 top-2'>
            {!isPreview && <AddComponentButton onClick={() => onAddComponent?.(position, true)} section={true} />}
          </div>
          <RenderComponents
            elements={elements}
            options={{
              iconSize: 12,
              controlsPosition: 'top-right',
            }}
            isInSection={true}
          />
          <div className='absolute left-0 right-0 -bottom-1'>
            {!isPreview && <AddComponentButton onClick={() => onAddComponent?.(position, false)} section={true} />}
          </div>
        </div>
      ) : (
        !isPreview && (
          <div className='min-h-[200px] flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-[var(--color-text)]/20 p-8'>
            <p className='text-sm text-[var(--color-text)]/70'>{position} column is empty</p>
            <AddComponentButton onClick={() => onAddComponent?.(position)} variant='visible' />
          </div>
        )
      )}
    </div>
  );

  return (
    <Wrapper id={sectionId} className={cn('flex flex-col md:flex-row gap-8', className)} styling={styling}>
      {renderColumn('left', leftChildren)}
      {renderColumn('middle', middleChildren)}
      {renderColumn('right', rightChildren)}
    </Wrapper>
  );
}
