'use client';

import React, { useState, useMemo } from 'react';
import { ICON_LIST, ICON_CATEGORIES, ICON_MAP } from '@/lib/puck/iconMap';

interface IconPickerFieldProps {
  value: string;
  onChange: (value: string) => void;
}

/**
 * Visual icon picker for Puck custom fields.
 * Shows a searchable grid of 55+ Lucide icons organized by category.
 */
export function IconPickerField({ value, onChange }: IconPickerFieldProps) {
  const [search, setSearch] = useState('');
  const [expanded, setExpanded] = useState(true);

  const filtered = useMemo(() => {
    if (!search) return ICON_LIST;
    const q = search.toLowerCase();
    return ICON_LIST.filter(
      (icon) =>
        icon.label.toLowerCase().includes(q) ||
        icon.name.toLowerCase().includes(q) ||
        icon.category.toLowerCase().includes(q)
    );
  }, [search]);

  // Group by category
  const grouped = useMemo(() => {
    const map: Record<string, typeof ICON_LIST> = {};
    for (const icon of filtered) {
      if (!map[icon.category]) map[icon.category] = [];
      map[icon.category].push(icon);
    }
    return map;
  }, [filtered]);

  const SelectedIcon = value ? ICON_MAP[value] : null;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
      {/* Current selection + toggle */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '6px 10px',
          border: '1px solid #d1d5db',
          borderRadius: '6px',
          background: '#fff',
          cursor: 'pointer',
        }}
        onClick={() => setExpanded(!expanded)}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          {SelectedIcon ? (
            <SelectedIcon className="" strokeWidth={1.5} />
          ) : (
            <span style={{ fontSize: '13px', color: '#94a3b8' }}>No icon selected</span>
          )}
          {value && (
            <span style={{ fontSize: '13px', color: '#374151', fontWeight: 500 }}>
              {ICON_LIST.find((i) => i.name === value)?.label || value}
            </span>
          )}
        </div>
        <svg
          width="14"
          height="14"
          viewBox="0 0 24 24"
          fill="none"
          stroke="#94a3b8"
          strokeWidth="2"
          style={{
            transform: expanded ? 'rotate(180deg)' : 'rotate(0deg)',
            transition: 'transform 0.2s',
          }}
        >
          <path d="m6 9 6 6 6-6" />
        </svg>
      </div>

      {expanded && (
        <>
          {/* Search */}
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search icons..."
            style={{
              padding: '6px 10px',
              fontSize: '13px',
              border: '1px solid #d1d5db',
              borderRadius: '6px',
              background: '#fff',
              color: '#1f2937',
              outline: 'none',
            }}
          />

          {/* Icon grid */}
          <div
            style={{
              maxHeight: '240px',
              overflowY: 'auto',
              border: '1px solid #e5e7eb',
              borderRadius: '8px',
              background: '#fafafa',
            }}
          >
            {Object.entries(grouped).map(([category, icons]) => (
              <div key={category}>
                <div
                  style={{
                    padding: '4px 10px',
                    fontSize: '10px',
                    fontWeight: 700,
                    textTransform: 'uppercase',
                    letterSpacing: '0.05em',
                    color: '#94a3b8',
                    background: '#f1f5f9',
                    borderBottom: '1px solid #e5e7eb',
                    position: 'sticky',
                    top: 0,
                    zIndex: 1,
                  }}
                >
                  {category}
                </div>
                <div
                  style={{
                    display: 'grid',
                    gridTemplateColumns: 'repeat(6, 1fr)',
                    gap: '2px',
                    padding: '4px',
                  }}
                >
                  {icons.map((icon) => {
                    const Icon = icon.component;
                    const isSelected = value === icon.name;
                    return (
                      <button
                        key={icon.name}
                        onClick={() => onChange(icon.name)}
                        title={icon.label}
                        style={{
                          display: 'flex',
                          flexDirection: 'column',
                          alignItems: 'center',
                          justifyContent: 'center',
                          padding: '6px 2px',
                          borderRadius: '6px',
                          border: isSelected ? '2px solid #2563eb' : '2px solid transparent',
                          background: isSelected ? '#eff6ff' : 'transparent',
                          cursor: 'pointer',
                          transition: 'all 0.1s',
                        }}
                        onMouseEnter={(e) => {
                          if (!isSelected) e.currentTarget.style.background = '#f1f5f9';
                        }}
                        onMouseLeave={(e) => {
                          if (!isSelected) e.currentTarget.style.background = 'transparent';
                        }}
                      >
                        <div style={{ width: '18px', height: '18px', color: isSelected ? '#2563eb' : '#64748b' }}>
                          <Icon className="w-full h-full" strokeWidth={1.5} />
                        </div>
                        <span
                          style={{
                            fontSize: '8px',
                            color: isSelected ? '#2563eb' : '#94a3b8',
                            marginTop: '2px',
                            lineHeight: '1',
                            textAlign: 'center',
                            maxWidth: '100%',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                          }}
                        >
                          {icon.label}
                        </span>
                      </button>
                    );
                  })}
                </div>
              </div>
            ))}

            {filtered.length === 0 && (
              <div style={{ padding: '16px', textAlign: 'center', color: '#94a3b8', fontSize: '13px' }}>
                No icons match "{search}"
              </div>
            )}
          </div>

          {/* Clear button */}
          {value && (
            <button
              onClick={() => onChange('')}
              style={{
                padding: '4px 8px',
                fontSize: '11px',
                color: '#64748b',
                background: '#f1f5f9',
                border: '1px solid #e2e8f0',
                borderRadius: '6px',
                cursor: 'pointer',
                alignSelf: 'flex-start',
              }}
            >
              Clear icon
            </button>
          )}
        </>
      )}
    </div>
  );
}
