// components/admin/page-builder/ComponentPalette.tsx
'use client';

import { useDraggable } from '@dnd-kit/core';
import { componentRegistry, ComponentType } from '@/lib/page-builder/component-registry';
import { useState, useMemo } from 'react';

function ComponentItem({ type }: { type: ComponentType }) {
  const config = componentRegistry[type];
  const { attributes, listeners, setNodeRef, isDragging } = useDraggable({
    id: `palette-${type}`,
    data: {
      type: type,
      from: 'palette'
    },
  });

  return (
    <div
      ref={setNodeRef}
      {...listeners}
      {...attributes}
      className={`
        p-4 border border-var-border rounded-lg cursor-grab bg-var-surface hover:shadow-var-card transition-all duration-200
        ${isDragging ? 'opacity-50 scale-95' : 'opacity-100'}
        active:cursor-grabbing
      `}
      style={{
        cursor: isDragging ? 'grabbing' : 'grab',
      }}
    >
      <div className="flex items-center gap-3">
        <span className="text-2xl">{config.icon}</span>
        <div className="flex-1 min-w-0">
          <h4 className="font-semibold text-var-text truncate">{type}</h4>
          <p className="text-sm text-var-text-muted truncate">{config.description}</p>
        </div>
      </div>
    </div>
  );
}

export default function ComponentPalette() {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string>('all');

  const components = Object.keys(componentRegistry) as ComponentType[];
  
  const categories = useMemo(() => {
    const uniqueCategories = new Set(components.map(type => componentRegistry[type].category));
    return ['all', ...Array.from(uniqueCategories)];
  }, [components]);

  const filteredComponents = useMemo(() => {
    return components.filter(type => {
      const config = componentRegistry[type];
      const matchesSearch = 
        type.toLowerCase().includes(searchQuery.toLowerCase()) ||
        config.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
        config.category.toLowerCase().includes(searchQuery.toLowerCase());
      
      const matchesCategory = selectedCategory === 'all' || config.category === selectedCategory;
      
      return matchesSearch && matchesCategory;
    });
  }, [components, searchQuery, selectedCategory]);

  return (
    <div className="w-80 bg-var-surface-hover border-r border-var-border p-4 overflow-y-auto flex flex-col">
      <h3 className="font-semibold text-lg text-var-text mb-4">Components</h3>
      
      {/* Search Bar */}
      <div className="mb-4">
        <div className="relative">
          <input
            type="text"
            placeholder="Search components..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full p-2 pl-9 border border-var-border rounded-lg focus:outline-none focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-input"
          />
          <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <svg className="h-4 w-4 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
          </div>
          {searchQuery && (
            <button
              onClick={() => setSearchQuery('')}
              className="absolute inset-y-0 right-0 pr-3 flex items-center"
            >
              <svg className="h-4 w-4 text-var-text-muted hover:text-var-text" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          )}
        </div>
      </div>

      {/* Category Filter */}
      <div className="mb-4">
        <div className="flex flex-wrap gap-1">
          {categories.map(category => (
            <button
              key={category}
              onClick={() => setSelectedCategory(category)}
              className={`px-3 py-1 text-xs rounded-full capitalize transition-colors ${
                selectedCategory === category
                  ? 'bg-var-primary text-white'
                  : 'bg-var-surface text-var-text-muted hover:bg-var-surface-hover'
              }`}
            >
              {category}
            </button>
          ))}
        </div>
      </div>

      {/* Results Count */}
      <div className="mb-3 text-sm text-var-text-muted">
        {filteredComponents.length} of {components.length} components
      </div>

      {/* Components List */}
      <div className="space-y-3 flex-1 overflow-y-auto">
        {filteredComponents.length > 0 ? (
          filteredComponents.map(type => (
            <ComponentItem key={type} type={type} />
          ))
        ) : (
          <div className="text-center py-8 text-var-text-muted">
            <svg className="w-12 h-12 mx-auto mb-2 text-var-text-disabled" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <p>No components found</p>
            <p className="text-sm">Try a different search term</p>
          </div>
        )}
      </div>
    </div>
  );
}