import React, { useState, useEffect, useCallback } from 'react';
import { FileText, RefreshCw, Building2, CheckCircle2, XCircle, Send, Clock } from 'lucide-react';
import { HybridBackend } from '../services/backend.ts';
import { useToast } from '../contexts/ToastContext.tsx';
import { PageHeader } from '../components/PageHeader.tsx';

const dataBR = (d: string) => (d || '').slice(0, 10).split('-').reverse().join('/');
const fmtBRL = (v: number) => 'R$ ' + Number(v || 0).toLocaleString('pt-BR', { minimumFractionDigits: 2 });

// Área do Laboratório (Fatia 3): pedidos de cotação recebidos das clínicas.
export const LabCotacoesView: React.FC = () => {
  const toast = useToast();
  const [lista, setLista] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [forms, setForms] = useState<Record<string, { valor: string; prazo: string; obs: string }>>({});
  const [busy, setBusy] = useState('');

  const carregar = useCallback(async () => {
    setLoading(true);
    try { const r = await HybridBackend.getRfqRecebidas(); setLista(Array.isArray(r) ? r : []); }
    catch { /* silent */ } finally { setLoading(false); }
  }, []);
  useEffect(() => { carregar(); }, [carregar]);

  const setF = (id: string, k: string, v: string) => setForms(s => ({ ...s, [id]: { ...(s[id] || { valor: '', prazo: '', obs: '' }), [k]: v } }));
  const responder = async (c: any) => {
    const f = forms[c.cotacao_id] || { valor: '', prazo: '', obs: '' };
    const valor = parseFloat(f.valor);
    if (!(valor > 0)) { toast.error('INFORME O VALOR.'); return; }
    setBusy(c.cotacao_id);
    try { await HybridBackend.responderCotacao(c.cotacao_id, { valor, prazo_dias: parseInt(f.prazo, 10) || undefined, observacao: f.obs.trim() || undefined }); toast.success('COTAÇÃO ENVIADA.'); carregar(); }
    catch (e: any) { toast.error((e.message || 'ERRO').toUpperCase()); } finally { setBusy(''); }
  };

  return (
    <div className="space-y-6 pb-10 max-w-2xl">
      <PageHeader title="PEDIDOS DE COTAÇÃO">
        <button onClick={carregar} className="bg-white border border-gray-200 text-gray-600 p-2 rounded-lg hover:bg-gray-50 flex items-center gap-2 text-xs font-bold shadow-sm"><RefreshCw size={16} /></button>
      </PageHeader>

      {loading ? <div className="flex justify-center py-16"><RefreshCw className="animate-spin text-teal-600" size={28} /></div>
        : lista.length === 0 ? <div className="py-16 text-center text-gray-400 font-bold uppercase text-sm">Nenhum pedido de cotação.</div>
          : (
            <div className="space-y-3">
              {lista.map(c => {
                const aberta = c.rfq_status === 'aberta';
                const ganhou = c.cotacao_status === 'escolhida';
                const perdeu = c.cotacao_status === 'recusada';
                const f = forms[c.cotacao_id] || { valor: '', prazo: '', obs: '' };
                return (
                  <div key={c.cotacao_id} className={`bg-white rounded-2xl border shadow-sm p-4 ${ganhou ? 'border-green-200' : 'border-gray-100'}`}>
                    <div className="flex items-start justify-between gap-2">
                      <div className="min-w-0">
                        <p className="font-black text-gray-800 text-sm">{c.descricao}</p>
                        <p className="text-[11px] text-gray-400 uppercase font-bold flex items-center gap-1 mt-0.5"><Building2 size={11} /> {c.clinica_nome || 'Clínica'}{c.dentes ? ` · dentes ${c.dentes}` : ''}</p>
                      </div>
                      {ganhou && <span className="text-[9px] font-black px-2 py-1 rounded-full bg-green-100 text-green-700 uppercase flex items-center gap-1 shrink-0"><CheckCircle2 size={11} /> Você ganhou</span>}
                      {perdeu && <span className="text-[9px] font-black px-2 py-1 rounded-full bg-gray-100 text-gray-500 uppercase flex items-center gap-1 shrink-0"><XCircle size={11} /> Não escolhida</span>}
                      {aberta && c.cotacao_status === 'enviada' && <span className="text-[9px] font-black px-2 py-1 rounded-full bg-amber-100 text-amber-700 uppercase shrink-0">Cotado · {fmtBRL(c.valor)}</span>}
                    </div>
                    {(c.paciente_nome || c.prazo_desejado) && <p className="text-[11px] text-gray-400 mt-2">{c.paciente_nome || ''}{c.prazo_desejado ? ` · prazo desejado ${dataBR(c.prazo_desejado)}` : ''}</p>}

                    {aberta && (
                      <div className="mt-3 pt-3 border-t border-gray-100 flex flex-wrap items-end gap-2">
                        <div>
                          <label className="text-[9px] font-black text-gray-400 uppercase block mb-1">Valor (R$)</label>
                          <input type="number" step="0.01" value={f.valor} onChange={e => setF(c.cotacao_id, 'valor', e.target.value)} placeholder={c.valor ? String(c.valor) : '0,00'} className="w-24 p-2 bg-gray-50 border border-gray-100 rounded-lg text-xs font-bold outline-none focus:border-teal-400" />
                        </div>
                        <div>
                          <label className="text-[9px] font-black text-gray-400 uppercase block mb-1">Prazo (dias)</label>
                          <input type="number" value={f.prazo} onChange={e => setF(c.cotacao_id, 'prazo', e.target.value)} className="w-20 p-2 bg-gray-50 border border-gray-100 rounded-lg text-xs font-bold outline-none focus:border-teal-400" />
                        </div>
                        <input value={f.obs} onChange={e => setF(c.cotacao_id, 'obs', e.target.value)} placeholder="Observação" className="flex-1 min-w-[120px] p-2 bg-gray-50 border border-gray-100 rounded-lg text-xs outline-none focus:border-teal-400" />
                        <button disabled={busy === c.cotacao_id} onClick={() => responder(c)} className="px-3 py-2 rounded-lg bg-[#2d6a4f] text-white text-[11px] font-black uppercase disabled:opacity-50 flex items-center gap-1.5"><Send size={13} /> {c.cotacao_status === 'enviada' ? 'Atualizar' : 'Cotar'}</button>
                      </div>
                    )}
                    {!aberta && !ganhou && !perdeu && <p className="text-[10px] text-gray-400 uppercase font-bold mt-2 flex items-center gap-1"><Clock size={11} /> Encerrado</p>}
                  </div>
                );
              })}
            </div>
          )}
    </div>
  );
};
