'use client';
import { useState } from 'react';
import { PortfolioElement } from '@/src/types/portfolio';
import { RenderComponent } from './config/renderComponent';
import { ComponentSelector } from './ComponentSelector';
import { AddComponentButton } from './common/AddComponentButton';
import { ComponentType } from './config/componentRegistry';
import { useBuilder } from './context/BuilderContext';

interface PortfolioCanvasProps {
  elements: PortfolioElement[];
  isPreview?: boolean;
}

export function PortfolioCanvas({ elements, isPreview }: PortfolioCanvasProps) {
  const { onAddComponent, onAddToSection } = useBuilder();
  const [showSelector, setShowSelector] = useState(false);
  const [insertPosition, setInsertPosition] = useState<number>(-1);
  const [sectionContext, setSectionContext] = useState<{
    parentId: string;
    position: string;
    top?: boolean;
  } | null>(null);

  const hasHeader = elements.some((element) => element.layout.startsWith('header_'));

  const handleComponentSelect = (componentType: ComponentType, initialProps?: Partial<PortfolioElement['props']>) => {
    if (sectionContext) {
      onAddToSection(sectionContext.parentId, sectionContext.position, componentType, initialProps, sectionContext.top);
      setSectionContext(null);
    } else {
      const index = componentType.startsWith('header_') ? 0 : insertPosition >= 0 ? insertPosition : elements.length;
      onAddComponent(index, componentType, initialProps);
    }
    setShowSelector(false);
  };

  return (
    <div
      className='border-neutral-300 mx-auto mt-14 pt-6 h-full bg-[var(--color-background)] text-[var(--color-text)] min-h-[calc(100vh-7rem)]'
      style={{
        fontFamily: 'var(--text-font-family)',
      }}
    >
      <div className='pt-8'>
        {elements.length === 0 ? (
          <div className='flex flex-col items-center justify-center h-full gap-4 min-h-[calc(100vh-9rem)]'>
            <p className='text-neutral-500'>No components added yet</p>
            <AddComponentButton onClick={() => setShowSelector(true)} variant='visible' />
          </div>
        ) : (
          <div className='flex flex-col'>
            {elements.map((element, index) => (
              <div key={element.id} className='group relative'>
                {!isPreview && (
                  <AddComponentButton
                    position='top'
                    onClick={() => {
                      setShowSelector(true);
                      setInsertPosition(index);
                      setSectionContext(null);
                    }}
                  />
                )}
                <RenderComponent
                  element={element}
                  options={{ iconSize: 20, controlsPosition: 'top-left' }}
                  setSectionContext={setSectionContext}
                  setShowSelector={setShowSelector}
                />
                {!isPreview && (
                  <AddComponentButton
                    position='bottom'
                    onClick={() => {
                      setShowSelector(true);
                      setInsertPosition(index + 1);
                      setSectionContext(null);
                    }}
                  />
                )}
              </div>
            ))}
            {!isPreview && (
              <div className='opacity-0 group-hover:opacity-100 transition-opacity'>
                <AddComponentButton
                  onClick={() => {
                    setShowSelector(true);
                    setInsertPosition(elements.length);
                    setSectionContext(null);
                  }}
                />
              </div>
            )}
          </div>
        )}

        {showSelector && (
          <ComponentSelector
            onSelect={handleComponentSelect}
            onCancel={() => {
              setShowSelector(false);
              setSectionContext(null);
            }}
            disabledCategories={[
              ...(sectionContext ? ['sections', 'navigation'] : []),
              ...(hasHeader ? ['navigation'] : []),
            ]}
          />
        )}
      </div>
    </div>
  );
}
