import React, { useState, useEffect } from 'react';
import { Users, Stethoscope, Wrench, MapPin, Search, Phone, Mail, RefreshCw } from 'lucide-react';

const API_URL = (window as any).__API_URL__ || '';

const UF_LIST = ['','AC','AL','AM','AP','BA','CE','DF','ES','GO','MA','MG','MS','MT','PA','PB','PE','PI','PR','RJ','RN','RO','RR','RS','SC','SE','SP','TO'];

interface Profissional {
    id: string;
    nome: string;
    email: string;
    role: 'dentista' | 'protetico';
    estado: string;
    cidade: string;
    bairro: string;
    especialidade: string;
}

export const DiretorioProfissionaisView: React.FC = () => {
    const [lista, setLista] = useState<Profissional[]>([]);
    const [loading, setLoading] = useState(false);
    const [tipo, setTipo] = useState<'dentista' | 'protetico' | ''>('');
    const [estado, setEstado] = useState('');
    const [cidade, setCidade] = useState('');
    const [especialidade, setEspecialidade] = useState('');

    const fetchLista = async () => {
        setLoading(true);
        try {
            const token = localStorage.getItem('SCOREODONTO_AUTH_TOKEN');
            const params = new URLSearchParams();
            if (tipo)        params.set('tipo', tipo);
            if (estado)      params.set('estado', estado);
            if (cidade)      params.set('cidade', cidade);
            if (especialidade) params.set('especialidade', especialidade);
            const res = await fetch(`${API_URL}/api/profissionais-disponiveis?${params}`, {
                headers: { Authorization: `Bearer ${token}` },
            });
            if (res.ok) { const data = await res.json(); setLista(data); }
        } catch { /* silently fail */ }
        finally { setLoading(false); }
    };

    useEffect(() => { fetchLista(); }, []);

    return (
        <div className="max-w-4xl mx-auto space-y-6">
            <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-purple-100 rounded-xl flex items-center justify-center">
                    <Users size={20} className="text-purple-600" />
                </div>
                <div>
                    <h1 className="text-xl font-black text-gray-900 uppercase tracking-tight">Diretório de Profissionais</h1>
                    <p className="text-xs text-gray-500 font-medium">Dentistas e protéticos disponíveis para contratação</p>
                </div>
            </div>

            {/* Filtros */}
            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-4">
                    <div>
                        <label className="text-[10px] font-black text-gray-400 uppercase tracking-widest block mb-1">Tipo</label>
                        <select
                            value={tipo}
                            onChange={e => setTipo(e.target.value as any)}
                            className="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold text-gray-700 outline-none focus:border-purple-400"
                        >
                            <option value="">Todos</option>
                            <option value="dentista">Dentistas</option>
                            <option value="protetico">Protéticos</option>
                        </select>
                    </div>
                    <div>
                        <label className="text-[10px] font-black text-gray-400 uppercase tracking-widest block mb-1">Estado</label>
                        <select
                            value={estado}
                            onChange={e => setEstado(e.target.value)}
                            className="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold text-gray-700 outline-none focus:border-purple-400"
                        >
                            {UF_LIST.map(uf => <option key={uf} value={uf}>{uf || 'Todos os estados'}</option>)}
                        </select>
                    </div>
                    <div>
                        <label className="text-[10px] font-black text-gray-400 uppercase tracking-widest block mb-1">Cidade</label>
                        <input
                            type="text"
                            value={cidade}
                            onChange={e => setCidade(e.target.value.toUpperCase())}
                            placeholder="CAMPO GRANDE"
                            className="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold text-gray-700 outline-none focus:border-purple-400 uppercase"
                        />
                    </div>
                    <div>
                        <label className="text-[10px] font-black text-gray-400 uppercase tracking-widest block mb-1">Especialidade</label>
                        <input
                            type="text"
                            value={especialidade}
                            onChange={e => setEspecialidade(e.target.value.toUpperCase())}
                            placeholder="EX: ORTODONTIA"
                            className="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold text-gray-700 outline-none focus:border-purple-400 uppercase"
                        />
                    </div>
                </div>
                <button
                    onClick={fetchLista}
                    disabled={loading}
                    className="flex items-center gap-2 px-5 py-2.5 bg-purple-600 hover:bg-purple-700 text-white rounded-xl text-xs font-black uppercase tracking-widest transition-colors disabled:opacity-60"
                >
                    {loading ? <RefreshCw size={14} className="animate-spin" /> : <Search size={14} />}
                    Buscar
                </button>
            </div>

            {/* Lista */}
            {loading ? (
                <div className="flex justify-center py-12">
                    <RefreshCw size={24} className="animate-spin text-purple-400" />
                </div>
            ) : lista.length === 0 ? (
                <div className="text-center py-12 text-gray-400">
                    <Users size={40} className="mx-auto mb-3 opacity-40" />
                    <p className="font-bold text-sm uppercase">Nenhum profissional encontrado</p>
                    <p className="text-xs mt-1">Ajuste os filtros ou aguarde novos cadastros</p>
                </div>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {lista.map(p => (
                        <div key={p.id} className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 hover:border-purple-200 hover:shadow-md transition-all">
                            <div className="flex items-start gap-3 mb-3">
                                <div className={`w-10 h-10 rounded-xl flex items-center justify-center shrink-0 ${p.role === 'protetico' ? 'bg-violet-100' : 'bg-teal-100'}`}>
                                    {p.role === 'protetico'
                                        ? <Wrench size={18} className="text-violet-600" />
                                        : <Stethoscope size={18} className="text-teal-600" />
                                    }
                                </div>
                                <div className="flex-1 min-w-0">
                                    <div className="flex items-center gap-2 flex-wrap">
                                        <span className="font-black text-gray-900 text-sm uppercase truncate">{p.nome}</span>
                                        <span className={`text-[9px] font-black px-2 py-0.5 rounded-full uppercase ${p.role === 'protetico' ? 'bg-violet-100 text-violet-700' : 'bg-teal-100 text-teal-700'}`}>
                                            {p.role === 'protetico' ? 'Protético' : 'Dentista'}
                                        </span>
                                    </div>
                                    {p.especialidade && (
                                        <p className="text-xs text-gray-500 font-medium mt-0.5 uppercase">{p.especialidade}</p>
                                    )}
                                </div>
                            </div>

                            <div className="space-y-1.5">
                                {(p.cidade || p.estado) && (
                                    <div className="flex items-center gap-1.5 text-xs text-gray-500 font-medium">
                                        <MapPin size={12} className="shrink-0 text-gray-400" />
                                        <span>{[p.bairro, p.cidade, p.estado].filter(Boolean).join(' · ')}</span>
                                    </div>
                                )}
                                <div className="flex items-center gap-1.5 text-xs text-gray-500 font-medium">
                                    <Mail size={12} className="shrink-0 text-gray-400" />
                                    <span>{p.email}</span>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
};
