'use client';
import { ComponentStyler } from '@/components/builder/common/ComponentStyler';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { PortfolioElement } from '@/src/types/portfolio';
import { TimelinePropsItem } from '@/src/types/timeline';
import { EditFormProps } from '@/types/common';
import { DEFAULT_ITEM, getItemKey } from '@/utils/timeline';
import { Plus } from 'lucide-react';
import { useEffect, useState } from 'react';
import { TimelineItemEditor } from './TimelineItemEditor';
import { TimelineItemSummary } from './TimelineItemSummary';

export function TimelineEditForm({ props, onPropChange, layout }: EditFormProps) {
  const timelineData: TimelinePropsItem[] = (props.timelineData ?? []) as TimelinePropsItem[];
  const [editingIndex, setEditingIndex] = useState<number | null>(null);
  const [editingItem, setEditingItem] = useState<TimelinePropsItem | null>(null);
  const [itemKeys] = useState<Record<number, string>>({});

  useEffect(() => {
    setEditingIndex(null);
    setEditingItem(null);
  }, [props.id]);

  const handleAddItem = () => {
    const updatedData = [...timelineData, DEFAULT_ITEM];
    onPropChange('timelineData', updatedData);
    setEditingIndex(updatedData.length - 1);
    setEditingItem(DEFAULT_ITEM);
  };

  const handleCloseEdit = () => {
    setEditingIndex(null);
    setEditingItem(null);
  };

  const handleUpdateItem = (updatedItem: TimelinePropsItem) => {
    if (editingIndex === null) return;

    setEditingItem(updatedItem);
    const updatedData = [...timelineData];
    updatedData[editingIndex] = updatedItem;
    onPropChange('timelineData', updatedData);
  };

  const handleRemoveItem = (index: number) => {
    const updatedData = timelineData.filter((_, i) => i !== index);
    onPropChange('timelineData', updatedData);

    if (editingIndex === index) {
      setEditingIndex(null);
      setEditingItem(null);
    }
  };

  return (
    <div className='space-y-6'>
      <div className='space-y-4'>
        <div className='flex justify-between items-center py-2'>
          <Label>Timeline Items</Label>
        </div>

        {timelineData.map((item, index) => (
          <div
            key={getItemKey(index, itemKeys)}
            className='border border-neutral-700 rounded-lg p-2 space-y-4 bg-neutral-200 text-neutral-800'
          >
            {editingIndex === index ? (
              <TimelineItemEditor
                item={editingItem || item}
                onUpdate={handleUpdateItem}
                onClose={handleCloseEdit}
                index={index}
              />
            ) : (
              <TimelineItemSummary
                item={item}
                onEdit={() => {
                  setEditingIndex(index);
                  setEditingItem({ ...item });
                }}
                onRemove={() => handleRemoveItem(index)}
              />
            )}
          </div>
        ))}

        <Button onClick={handleAddItem} variant='light-outline' className='w-full'>
          <Plus className='h-4 w-4 mr-2' />
          Add Timeline Item
        </Button>
      </div>

      <ComponentStyler
        styling={props.styling as PortfolioElement['styling']}
        onStylingChange={(styling) => onPropChange('styling', styling)}
        enabledOptions={{
          backgroundColor: true,
          padding: true,
          alignment: layout === 'timeline_2' || layout === 'timeline_4',
          color: true,
        }}
      />
    </div>
  );
}
