/* global React, Card, Badge, Button, Avatar, Icon, ICONS, Field, sb */
const { useState, useEffect } = React;

const STATUS_MAP = {
  andamento: { tone: 'brand',   label: 'Em andamento' },
  ativo:     { tone: 'brand',   label: 'Em andamento' },
  revisao:   { tone: 'warning', label: 'Em revisão'   },
  pausa:     { tone: 'cyan',    label: 'Em pausa'     },
  quase:     { tone: 'success', label: 'Quase pronto' },
  concluido: { tone: 'neutral', label: 'Concluído'    },
};

const GRADIENTS = [
  'linear-gradient(135deg,#1D39C4 0%,#36CFC9 100%)',
  'linear-gradient(135deg,#FA541C,#FADB14)',
  'linear-gradient(135deg,#13C2C2,#1890FF)',
  'linear-gradient(135deg,#7C3AED,#1D39C4)',
  'linear-gradient(135deg,#1890FF,#34E0A1)',
  'linear-gradient(135deg,#FA541C,#FF6A6A)',
];

function daysUntil(dateStr) {
  if (!dateStr) return '—';
  const diff = Math.ceil((new Date(dateStr) - new Date()) / 86400000);
  if (diff < 0) return 'Atrasado';
  if (diff === 0) return 'Hoje';
  return `${diff} dias`;
}

function fmtBudget(v) {
  if (!v && v !== 0) return '—';
  return 'R$ ' + Number(v).toLocaleString('pt-BR');
}

function rowToProject(row, idx) {
  if (!row) return null;
  const sm = STATUS_MAP[row.status] || STATUS_MAP['andamento'] || { tone: 'brand', label: 'Em andamento' };
  return {
    id:        row.id,
    name:      row.name,
    client:    row.client || '',
    status:    sm.tone,
    sLab:      sm.label,
    dbStatus:  row.status || 'andamento',
    pct:       row.progress || 0,
    due:       daysUntil(row.deadline),
    tasks:     '—',
    value:     fmtBudget(row.budget),
    rawValue:  row.budget || 0,
    budget:    row.budget || 0,
    gradient:  row.gradient || GRADIENTS[idx % GRADIENTS.length],
    description: row.description,
    deadline:  row.deadline,
  };
}

function Projects({ onOpenProject }) {
  const [projects,       setProjects]       = useState([]);
  const [loading,        setLoading]        = useState(true);
  const [filter,         setFilter]         = useState('todos');
  const [filtOpen,       setFiltOpen]       = useState(false);
  const [team,           setTeam]           = useState(new Set(['AS','MR','JP']));
  const [valRange,       setValRange]       = useState('todos');
  const [dueRange,       setDueRange]       = useState('todos');
  const [menuOpen,       setMenuOpen]       = useState(null); // id do projeto com menu aberto
  const [confirmDelete,  setConfirmDelete]  = useState(null); // id do projeto a deletar
  const [deleting,       setDeleting]       = useState(false);

  async function handleDelete(projId) {
    setDeleting(true);
    const { error } = await sb.from('projects').delete().eq('id', projId);
    if (error) {
      window.__toast?.(error.message, { tone: 'danger' });
    } else {
      setProjects(prev => prev.filter(p => p.id !== projId));
      window.__toast?.('Projeto excluído com sucesso', { tone: 'success' });
    }
    setDeleting(false);
    setConfirmDelete(null);
    setMenuOpen(null);
  }

  useEffect(() => {
    (async () => {
      try {
        const { data, error } = await sb.from('projects').select('*').order('created_at', { ascending: false });
        if (error) { window.__toast?.(error.message, { tone: 'danger' }); }
        setProjects((data || []).map(rowToProject).filter(Boolean));
      } catch(e) {
        console.error('[Projects] erro ao carregar:', e);
        window.__toast?.('Erro ao carregar projetos', { tone: 'danger' });
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  const filtCount = (team.size !== 3 ? 1 : 0) + (valRange !== 'todos' ? 1 : 0) + (dueRange !== 'todos' ? 1 : 0);

  const counts = {
    todos:     projects.length,
    andamento: projects.filter(p => p.dbStatus === 'andamento' || p.dbStatus === 'ativo').length,
    revisao:   projects.filter(p => p.dbStatus === 'revisao').length,
    pausa:     projects.filter(p => p.dbStatus === 'pausa').length,
    concluido: projects.filter(p => p.dbStatus === 'concluido' || p.dbStatus === 'quase').length,
  };

  const filters = [
    { id: 'todos',     lab: 'Todos',        count: counts.todos },
    { id: 'andamento', lab: 'Em andamento', count: counts.andamento },
    { id: 'revisao',   lab: 'Em revisão',   count: counts.revisao },
    { id: 'pausa',     lab: 'Em pausa',     count: counts.pausa },
    { id: 'concluido', lab: 'Concluído',    count: counts.concluido },
  ];

  const filtered = projects.filter(p => {
    if (filter !== 'todos') {
      if (filter === 'andamento' && p.dbStatus !== 'andamento' && p.dbStatus !== 'ativo') return false;
      if (filter !== 'andamento' && p.dbStatus !== filter) return false;
    }
    if (valRange === 'ate10'  && p.rawValue > 10000) return false;
    if (valRange === 'ate20'  && (p.rawValue <= 10000 || p.rawValue > 20000)) return false;
    if (valRange === 'acima'  && p.rawValue <= 20000) return false;
    const days = parseInt(p.due);
    if (dueRange === 'urgente' && (p.due === '—' || isNaN(days) || days > 7)) return false;
    if (dueRange === 'mes'     && (p.due === '—' || isNaN(days) || days > 30)) return false;
    if (dueRange === 'sem'     && p.due !== '—') return false;
    return true;
  });

  if (loading) {
    return <div style={{ padding: 40, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 14 }}>Carregando projetos…</div>;
  }

  return (
    <div style={{ padding: '24px 28px', display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        {filters.map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)}
            style={{
              display: 'flex', alignItems: 'center', gap: 8,
              padding: '8px 14px', borderRadius: 999,
              background: filter === f.id ? 'var(--primary)' : 'var(--bg-surface)',
              color: filter === f.id ? '#fff' : 'var(--fg-secondary)',
              border: `1px solid ${filter === f.id ? 'var(--primary)' : 'var(--border-subtle)'}`,
              fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer',
            }}>
            {f.lab}
            <span style={{
              fontSize: 10, padding: '1px 7px', borderRadius: 999, fontFamily: 'var(--font-mono)',
              background: filter === f.id ? 'rgba(255,255,255,0.2)' : 'var(--bg-elevated)',
              color: filter === f.id ? '#fff' : 'var(--fg-muted)',
            }}>{f.count}</span>
          </button>
        ))}
        <div style={{ flex: 1 }} />
        <div style={{ position: 'relative' }}>
          <Button variant="secondary" icon="filter" onClick={() => setFiltOpen(o => !o)}>
            Mais filtros{filtCount > 0 && <span style={{ marginLeft: 6, background: 'var(--accent-primary)', color: '#fff', fontSize: 10, fontFamily: 'var(--font-mono)', fontWeight: 700, padding: '1px 5px', borderRadius: 4 }}>{filtCount}</span>}
          </Button>
          {filtOpen && (
            <>
              <div onClick={() => setFiltOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 40 }}/>
              <div style={{ position: 'absolute', top: 'calc(100% + 6px)', right: 0, zIndex: 50, width: 300, background: 'var(--bg-surface)', border: '1px solid var(--border-strong)', borderRadius: 12, boxShadow: '0 16px 40px rgba(0,0,0,0.5)', padding: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Equipe</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {['AS','MR','JP','LV','CT'].map((n, i) => {
                    const on = team.has(n);
                    return (
                      <button key={n} onClick={() => { const next = new Set(team); on ? next.delete(n) : next.add(n); setTeam(next); }} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '4px 8px 4px 4px', borderRadius: 999, border: `1px solid ${on ? 'var(--accent-primary)' : 'var(--border-subtle)'}`, background: on ? 'rgba(29,57,196,0.12)' : 'transparent', cursor: 'pointer', fontSize: 12, color: 'var(--fg-primary)' }}>
                        <Avatar name={n} size={20} idx={i}/>{n}
                      </button>
                    );
                  })}
                </div>
                <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Valor</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {[['todos','Todos'],['ate10','até R$ 10k'],['ate20','R$ 10–20k'],['acima','acima R$ 20k']].map(([v, l]) => (
                    <button key={v} onClick={() => setValRange(v)} style={{ padding: '5px 10px', borderRadius: 999, border: `1px solid ${valRange === v ? 'var(--accent-primary)' : 'var(--border-subtle)'}`, background: valRange === v ? 'var(--accent-primary)' : 'transparent', color: valRange === v ? '#fff' : 'var(--fg-secondary)', cursor: 'pointer', fontSize: 12 }}>{l}</button>
                  ))}
                </div>
                <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Prazo</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {[['todos','Todos'],['urgente','até 7 dias'],['mes','até 30 dias'],['sem','sem prazo']].map(([v, l]) => (
                    <button key={v} onClick={() => setDueRange(v)} style={{ padding: '5px 10px', borderRadius: 999, border: `1px solid ${dueRange === v ? 'var(--accent-primary)' : 'var(--border-subtle)'}`, background: dueRange === v ? 'var(--accent-primary)' : 'transparent', color: dueRange === v ? '#fff' : 'var(--fg-secondary)', cursor: 'pointer', fontSize: 12 }}>{v === 'todos' ? l : l}</button>
                  ))}
                </div>
                <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 4, borderTop: '1px solid var(--border-subtle)', paddingTop: 12 }}>
                  <Button variant="ghost" size="sm" onClick={() => { setTeam(new Set(['AS','MR','JP'])); setValRange('todos'); setDueRange('todos'); }}>Limpar</Button>
                  <Button size="sm" onClick={() => setFiltOpen(false)}>Aplicar</Button>
                </div>
              </div>
            </>
          )}
        </div>
      </div>

      {filtered.length === 0 && !loading && (
        <div style={{ padding: '48px 24px', textAlign: 'center', color: 'var(--fg-muted)' }}>
          <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 6 }}>Nenhum projeto ainda</div>
          <div style={{ fontSize: 13 }}>Clique em "Novo projeto" para começar.</div>
        </div>
      )}

      {/* Modal de confirmação de exclusão */}
      {confirmDelete && (
        <div style={{ position:'fixed', inset:0, background:'rgba(7,11,28,0.75)', backdropFilter:'blur(6px)', display:'grid', placeItems:'center', zIndex:9999, padding:24 }}
          onClick={() => { if (!deleting) setConfirmDelete(null); }}>
          <div onClick={e => e.stopPropagation()} style={{ width:'min(420px,100%)', background:'var(--bg-surface)', border:'1px solid rgba(239,68,68,0.3)', borderRadius:16, padding:'32px 32px 24px', display:'flex', flexDirection:'column', gap:0 }}>
            <div style={{ fontSize:18, fontWeight:800, marginBottom:8 }}>Excluir projeto?</div>
            <p style={{ margin:'0 0 24px', fontSize:14, color:'var(--fg-secondary)', lineHeight:1.6 }}>
              Esta ação não pode ser desfeita. O projeto e todos os dados associados serão removidos permanentemente.
            </p>
            <div style={{ display:'flex', gap:10 }}>
              <button onClick={() => setConfirmDelete(null)} disabled={deleting}
                style={{ flex:1, padding:'12px 0', borderRadius:10, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', color:'var(--fg-primary)', fontSize:14, fontWeight:600, cursor:'pointer', fontFamily:'inherit' }}>
                Cancelar
              </button>
              <button onClick={() => handleDelete(confirmDelete)} disabled={deleting}
                style={{ flex:1, padding:'12px 0', borderRadius:10, border:'none', background:'rgba(239,68,68,0.9)', color:'#fff', fontSize:14, fontWeight:700, cursor:deleting?'not-allowed':'pointer', fontFamily:'inherit', opacity:deleting?0.7:1 }}>
                {deleting ? 'Excluindo…' : 'Sim, excluir'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Overlay para fechar menu ao clicar fora */}
      {menuOpen && <div onClick={() => setMenuOpen(null)} style={{ position:'fixed', inset:0, zIndex:40 }}/>}

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18 }}>
        {filtered.map((p, i) => (
          <div key={p.id} style={{ position: 'relative' }}>
            <Card hoverable padding={0} onClick={() => onOpenProject(p)} style={{ overflow: 'hidden' }}>
              <div style={{ height:96, background:p.gradient, display:'flex', alignItems:'flex-end', padding:14 }}>
                <Badge tone={p.status}>{p.sLab}</Badge>
              </div>
              <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 12 }}>
                <div>
                  <div style={{ fontSize: 15, fontWeight: 700, lineHeight: 1.3 }}>{p.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 2 }}>Cliente: {p.client}</div>
                </div>
                <div style={{ height: 6, background: 'var(--bg-elevated)', borderRadius: 999, overflow: 'hidden' }}>
                  <div style={{ width: p.pct + '%', height: '100%', background: 'linear-gradient(90deg,#1D39C4,#36CFC9)' }}/>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--fg-muted)', fontFamily: 'var(--font-mono)' }}>
                  <span>{p.tasks} tarefas</span><span>{p.due}</span><span>{p.value}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div style={{ display: 'flex' }}>
                    {['AS','MR','JP'].slice(0, 2 + (i % 2)).map((n, j) => (
                      <Avatar key={j} name={n} idx={j + i} size={26}/>
                    ))}
                  </div>
                  <span style={{ fontSize: 12, color: 'var(--geek-blue-300)', fontWeight: 600 }}>Abrir →</span>
                </div>
              </div>
            </Card>
            {/* Botão ··· fora do Card para evitar overflow:hidden e conflito de click */}
            <div style={{ position:'absolute', top:10, right:10, zIndex:50 }} onClick={e => e.stopPropagation()}>
              <button
                onClick={() => setMenuOpen(menuOpen === p.id ? null : p.id)}
                style={{ background:'rgba(0,0,0,0.3)', border:'none', borderRadius:7, width:30, height:30, display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', color:'rgba(255,255,255,0.9)', backdropFilter:'blur(4px)' }}>
                <Icon d={ICONS.more} size={15}/>
              </button>
              {menuOpen === p.id && (
                <div style={{ position:'absolute', top:'calc(100% + 6px)', right:0, background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:10, boxShadow:'0 12px 32px rgba(0,0,0,0.5)', overflow:'hidden', minWidth:160 }}>
                  <button
                    onClick={() => { setConfirmDelete(p.id); setMenuOpen(null); }}
                    style={{ display:'flex', alignItems:'center', gap:10, width:'100%', padding:'11px 14px', background:'transparent', border:'none', color:'#F87171', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit', textAlign:'left' }}>
                    🗑 Excluir projeto
                  </button>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
window.Projects = Projects;
