// app/components/admin/page-builder/ComponentPickerModal.tsx
'use client';

import { useState, useMemo } from 'react';
import { componentRegistry } from '@/lib/page-builder/component-registry';
import { ComponentType } from '@/lib/page-builder/types';

interface ComponentPickerModalProps {
  isOpen: boolean;
  onClose: () => void;
  onPick: (type: ComponentType) => void;
  exclude?: ComponentType[];
}

export function ComponentPickerModal({
  isOpen,
  onClose,
  onPick,
  exclude = ['Container'],
}: ComponentPickerModalProps) {
  const [search, setSearch] = useState('');
  const [category, setCategory] = useState('all');

  const allTypes = (Object.keys(componentRegistry) as ComponentType[]).filter(
    t => !exclude.includes(t)
  );

  const categories = useMemo(() => {
    const cats = new Set(allTypes.map(t => componentRegistry[t].category));
    return ['all', ...Array.from(cats)];
  }, [allTypes]);

  const filtered = useMemo(() =>
    allTypes.filter(t => {
      const cfg = componentRegistry[t];
      const matchSearch =
        t.toLowerCase().includes(search.toLowerCase()) ||
        cfg.description.toLowerCase().includes(search.toLowerCase());
      const matchCat = category === 'all' || cfg.category === category;
      return matchSearch && matchCat;
    }),
    [allTypes, search, category]
  );

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={onClose} />

      {/* Modal */}
      <div className="relative bg-var-surface rounded-2xl shadow-var-modal w-full max-w-lg max-h-[75vh] flex flex-col overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b border-var-border">
          <div>
            <h2 className="text-base font-semibold text-var-text">Add Component</h2>
            <p className="text-xs text-var-text-muted mt-0.5">Pick a component to add inside the container</p>
          </div>
          <button
            onClick={onClose}
            className="w-8 h-8 flex items-center justify-center rounded-lg text-var-text-muted hover:text-var-text hover:bg-var-surface-hover transition-colors"
          >
            <svg className="w-4 h-4" 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>

        {/* Search */}
        <div className="px-5 pt-4 pb-2">
          <div className="relative">
            <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-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>
            <input
              autoFocus
              type="text"
              placeholder="Search components..."
              value={search}
              onChange={e => setSearch(e.target.value)}
              className="w-full pl-9 pr-4 py-2 bg-var-input border border-var-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-var-primary focus:border-var-primary text-var-text placeholder-var-input"
            />
          </div>
        </div>

        {/* Category tabs */}
        <div className="px-5 pb-3 flex gap-1.5 flex-wrap">
          {categories.map(cat => (
            <button
              key={cat}
              onClick={() => setCategory(cat)}
              className={`px-3 py-1 rounded-full text-xs font-medium capitalize transition-colors ${
                category === cat
                  ? 'bg-var-primary text-white'
                  : 'bg-var-surface-hover text-var-text-muted hover:bg-var-surface-hover'
              }`}
            >
              {cat}
            </button>
          ))}
        </div>

        {/* Grid of components */}
        <div className="flex-1 overflow-y-auto px-5 pb-5">
          {filtered.length === 0 ? (
            <div className="text-center py-10 text-var-text-muted text-sm">No components found</div>
          ) : (
            <div className="grid grid-cols-2 gap-3">
              {filtered.map(type => {
                const cfg = componentRegistry[type];
                return (
                  <button
                    key={type}
                    onClick={() => { onPick(type); onClose(); setSearch(''); }}
                    className="flex items-start gap-3 p-3.5 border border-var-border rounded-xl bg-var-surface hover:border-var-primary hover:bg-var-primary-muted hover:shadow-var-card transition-all text-left group"
                  >
                    <span className="text-2xl mt-0.5 shrink-0">{cfg.icon}</span>
                    <div className="min-w-0">
                      <p className="text-sm font-semibold text-var-text group-hover:text-var-primary-text truncate">{type}</p>
                      <p className="text-xs text-var-text-muted leading-snug mt-0.5 line-clamp-2">{cfg.description}</p>
                    </div>
                  </button>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}