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

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

  const getColumnWidths = () => {
    switch (leftWidth) {
      case 'small':
        return ['lg:w-1/3', 'lg:w-2/3'];
      case 'large':
        return ['lg:w-2/3', 'lg:w-1/3'];
      default:
        return ['lg:w-1/2', 'lg:w-1/2'];
    }
  };

  const [leftColumnWidth, rightColumnWidth] = getColumnWidths();

  const renderColumn = (position: 'left' | 'right', elements: PortfolioElement[], width: string) => (
    <div className={cn('w-full', width)}>
      {elements.length > 0 ? (
        <div className='flex flex-col space-y-4 relative'>
          <div className='absolute left-0 right-0 top-5'>
            {!isPreview && <AddComponentButton onClick={() => onAddComponent?.(position, true)} section={true} />}
          </div>
          {elements.map((element) => (
            <div key={element.id}>
              <RenderComponent
                element={element}
                options={{ controlsPosition: 'top-right', iconSize: 12 }}
                isInSection={true}
              />
            </div>
          ))}
          <div className='absolute left-0 right-0 bottom-0'>
            {!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-2'>
            <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-6 w-full', className)} styling={styling}>
      {renderColumn('left', leftChildren, leftColumnWidth)}
      {renderColumn('right', rightChildren, rightColumnWidth)}
    </Wrapper>
  );
}
