'use client';
import { PortfolioElement } from '@/src/types/portfolio';
import { useEffect, useState } from 'react';
import { components, isValidComponentName } from './config/componentRegistry';
import { Slider } from './common/Slider';
import { useBuilder } from './context/BuilderContext';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

interface EditPanelProps {
  selectedElement: PortfolioElement | null;
  onClose: () => void;
  isOpen: boolean;
  onToggleOpen: () => void;
}

export function EditPanel({ selectedElement, onClose, isOpen, onToggleOpen }: EditPanelProps) {
  const [props, setProps] = useState<Record<string, unknown> | null>(null);
  const { portfolioProjects, onElementUpdate } = useBuilder();

  useEffect(() => {
    if (selectedElement) {
      const elementProps = selectedElement.layout.startsWith('project_')
        ? { ...selectedElement.props, projects: portfolioProjects }
        : selectedElement.props;
      setProps(elementProps);
    } else {
      setProps(null);
    }
  }, [selectedElement, portfolioProjects]);

  const handlePropChange = (key: string, value: PortfolioElement['props'][string]) => {
    const newProps = {
      ...props,
      [key]: value,
    };
    setProps(newProps);
    onElementUpdate(selectedElement!.id, newProps);
  };

  const handleClose = () => {
    onClose();
  };

  const renderEditForm = () => {
    if (!selectedElement || !props) return null;

    if (isValidComponentName(selectedElement.layout)) {
      const componentConfig = components[selectedElement.layout];

      if ('editForm' in componentConfig) {
        const EditForm = componentConfig.editForm;
        return (
          <div className='space-y-4'>
            <div className='space-y-2'>
              <Label className='block text-sm font-medium text-neutral-200'>Section ID</Label>
              <Input
                type='text'
                value={(props.sectionId as string) ?? ''}
                onChange={(e) => handlePropChange('sectionId', e.target.value)}
                placeholder='section-id'
              />
              <p className='text-xs text-neutral-400'>Used for navigation in header.</p>
            </div>
            <EditForm props={props} onPropChange={handlePropChange} layout={selectedElement.layout} />
          </div>
        );
      }
    }

    return <div className='p-4 text-neutral-400'>No edit options available for this component.</div>;
  };

  if (!selectedElement || !props) {
    return null;
  }

  const title = components[selectedElement.layout].title;

  return (
    <Slider isOpen={isOpen} onToggle={onToggleOpen} side='right' title={'Edit ' + title} handleClose={handleClose}>
      <div className='p-4'>{renderEditForm()}</div>
    </Slider>
  );
}
