import React, { useState } from 'react';
import {
  Minus,
  User,
  Server,
  Cloud,
  CloudDownload,
  Headphones,
  Settings,
  Box,
  ClipboardCheck,
  Wifi,
  Phone,
  Mail,
  Link,
  Wrench,
  Briefcase,
  Database,
  ShieldCheck,
  CalendarCheck,
  FileText,
  Folder,
  Key,
  Globe,
  Cpu,
  HardDrive,
  LineChart,
  Lock
} from 'lucide-react';
import { cn } from '@/lib/utils';

/**
 * Ícones Lucide já utilizados no sistema — usados no painel de seleção.
 * { lucide: nome do componente, label: texto exibido }
 */
const LUCIDE_ICONS = [
  { lucide: 'User', label: 'User', Icon: User },
  { lucide: 'Server', label: 'Server', Icon: Server },
  { lucide: 'HardDrive', label: 'HDD', Icon: HardDrive },
  { lucide: 'Cloud', label: 'Cloud', Icon: Cloud },
  { lucide: 'CloudDownload', label: 'Cloud Download', Icon: CloudDownload },
  { lucide: 'Headphones', label: 'Headset', Icon: Headphones },
  { lucide: 'Settings', label: 'Config', Icon: Settings },
  { lucide: 'Box', label: 'Box', Icon: Box },
  { lucide: 'ClipboardCheck', label: 'Clipboard', Icon: ClipboardCheck },
  { lucide: 'Wifi', label: 'Wifi', Icon: Wifi },
  { lucide: 'Phone', label: 'Telefone', Icon: Phone },
  { lucide: 'Mail', label: 'E-mail', Icon: Mail },
  { lucide: 'Link', label: 'Link', Icon: Link },
  { lucide: 'Wrench', label: 'Ferramentas', Icon: Wrench },
  { lucide: 'Briefcase', label: 'Briefcase', Icon: Briefcase },
  { lucide: 'Database', label: 'Database', Icon: Database },
  { lucide: 'ShieldCheck', label: 'Shield', Icon: ShieldCheck },
  { lucide: 'CalendarCheck', label: 'Calendário', Icon: CalendarCheck },
  { lucide: 'FileText', label: 'Arquivo', Icon: FileText },
  { lucide: 'Folder', label: 'Pasta', Icon: Folder },
  { lucide: 'LineChart', label: 'Gráfico', Icon: LineChart },
  { lucide: 'Lock', label: 'Cadeado', Icon: Lock },
  { lucide: 'Key', label: 'Chave', Icon: Key },
  { lucide: 'Globe', label: 'Globe', Icon: Globe },
  { lucide: 'Cpu', label: 'CPU', Icon: Cpu }
];

const LUCIDE_MAP = Object.fromEntries(LUCIDE_ICONS.map((x) => [x.lucide, x]));

/** Valor armazenado: "lucide:Server" (prefixo lucide:) */
const PREFIX = 'lucide:';

export function parseImagemToIconName(imagem) {
  if (!imagem || typeof imagem !== 'string') return '';
  if (imagem.startsWith(PREFIX)) return imagem.slice(PREFIX.length).trim();
  const m = imagem.match(/bi bi-([a-z0-9-]+)/i);
  return m ? m[1] : '';
}

/** Gera valor armazenado a partir do nome Lucide. */
export function iconNameToImagem(name) {
  if (!name || typeof name !== 'string') return '';
  const n = name.trim();
  return n ? `${PREFIX}${n}` : '';
}

export function IconPicker({ value = '', onChange, className }) {
  const [custom, setCustom] = useState('');
  const raw = parseImagemToIconName(value);
  const currentLucide = raw && LUCIDE_MAP[raw] ? raw : value.startsWith(PREFIX) ? raw : '';

  const handleSelect = (name) => {
    if (name === '__none__') {
      onChange('');
      setCustom('');
      return;
    }
    if (name === '__custom__') {
      const n = custom.trim().replace(/^lucide:?/i, '');
      onChange(n ? `${PREFIX}${n}` : '');
      return;
    }
    onChange(iconNameToImagem(name));
    setCustom('');
  };

  return (
    <div className={cn('space-y-3', className)}>
      <div className="grid grid-cols-6 sm:grid-cols-8 gap-1.5 max-h-40 overflow-y-auto p-1 rounded-lg bg-slate-800/50 border border-slate-700">
        <button
          type="button"
          onClick={() => handleSelect('__none__')}
          className={cn(
            'flex flex-col items-center justify-center gap-0.5 p-2 rounded-lg border text-slate-400 transition-all hover:bg-slate-700 hover:text-white hover:border-slate-600',
            !currentLucide && !value ? 'border-purple-500 bg-purple-500/10 text-purple-400' : 'border-slate-700'
          )}
          title="Nenhum ícone"
        >
          <Minus className="w-5 h-5" strokeWidth={2.5} />
          <span className="text-[9px] uppercase font-bold">Nenhum</span>
        </button>
        {LUCIDE_ICONS.map(({ lucide, label, Icon }) => (
          <button
            key={lucide}
            type="button"
            onClick={() => handleSelect(lucide)}
            className={cn(
              'flex flex-col items-center justify-center gap-0.5 p-2 rounded-lg border transition-all hover:bg-slate-700 hover:border-slate-600',
              currentLucide === lucide
                ? 'border-purple-500 bg-purple-500/10 text-purple-400'
                : 'border-slate-700 text-slate-400 hover:text-white'
            )}
            title={label}
          >
            <Icon className="w-5 h-5" />
            <span className="text-[9px] truncate w-full text-center">{label}</span>
          </button>
        ))}
      </div>
      <div className="flex items-center gap-2">
        <input
          type="text"
          value={custom}
          onChange={(e) => setCustom(e.target.value)}
          placeholder="Outro: lucide: NomeDoIcone"
          className="flex-1 h-8 px-2 rounded-lg bg-slate-800 border border-slate-700 text-white text-xs placeholder:text-slate-500"
        />
        <button
          type="button"
          onClick={() => handleSelect('__custom__')}
          className="h-8 px-3 rounded-lg bg-slate-700 hover:bg-slate-600 text-slate-300 text-xs font-medium"
        >
          Usar
        </button>
      </div>
    </div>
  );
}

export { LUCIDE_ICONS, LUCIDE_MAP, PREFIX };
