'use client';
import { ComponentPreview } from '@/src/components/builder/ComponentPreview';
import { ComponentType, components } from './config/componentRegistry';
import { useState } from 'react';
import { FileInput } from '@/components/ui/file-input';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { Button } from '@/components/ui/button';
import { PortfolioElement } from '@/src/types/portfolio';

export function ComponentGroupPreview({
  group,
  onLayoutSelect,
}: {
  group: string;
  onLayoutSelect: (componentType: ComponentType, initialProps?: Partial<PortfolioElement['props']>) => void;
}) {
  const [selectedComponent, setSelectedComponent] = useState<ComponentType | null>(null);
  const [uploadedImageUrl, setUploadedImageUrl] = useState<string | null>(null);
  const { handle, isLoading } = useApiWithToast();
  const layouts = Object.entries(components).filter(
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    ([_, component]) => component.group === group
  );

  const handleComponentClick = (componentType: ComponentType) => {
    if (componentType === 'image') {
      setSelectedComponent(componentType);
    } else {
      onLayoutSelect(componentType);
    }
  };

  const handleFileSelect = async (file: File | null) => {
    if (!file) {
      setUploadedImageUrl(null);
      return;
    }
    const formData = new FormData();
    formData.append('file', file);

    const data = await handle<{ publicUrl: string }>(
      fetch('/api/image', {
        method: 'POST',
        body: formData,
      })
    );
    if (data?.publicUrl) {
      setUploadedImageUrl(data.publicUrl);
    }
  };

  const handleConfirm = () => {
    if (uploadedImageUrl) {
      onLayoutSelect('image', { src: uploadedImageUrl });
      setSelectedComponent(null);
      setUploadedImageUrl(null);
    }
  };

  const handleCancel = () => {
    setSelectedComponent(null);
    setUploadedImageUrl(null);
  };

  if (selectedComponent === 'image') {
    return (
      <div>
        <div className='gap-4 flex flex-col'>
          <div className='flex items-center justify-between gap-2'>
            <div className='flex items-center gap-2'>
              <h3 className='text-lg font-medium text-neutral-900'>Upload Image</h3>
            </div>
            <Button
              variant='outline'
              onClick={() => setSelectedComponent(null)}
              className='text-neutral-500 hover:text-neutral-700'
            >
              Back to elements
            </Button>
          </div>

          <FileInput name='image' accept='image/*' onFileSelect={handleFileSelect} isLoading={isLoading} />

          {uploadedImageUrl && (
            <div className='flex gap-2 justify-end'>
              <Button variant='outline' onClick={handleCancel} className='text-neutral-600 hover:text-neutral-800'>
                Cancel
              </Button>
              <Button onClick={handleConfirm} className='bg-neutral-900 text-white hover:bg-neutral-800'>
                Add Image
              </Button>
            </div>
          )}
        </div>
      </div>
    );
  }

  return (
    <div className='flex flex-col space-y-2'>
      {layouts.map(([layoutName, layout]) => (
        <ComponentPreview
          key={layoutName}
          title={layout.title}
          preview={layout.preview}
          onClick={() => handleComponentClick(layoutName as ComponentType)}
        />
      ))}
    </div>
  );
}
