// Pacientes page — list view, grid view, patient detail

const { useState: pacState } = React;

/* ── Modal: Novo / Editar Paciente ── */
function ModalPacienteForm({ title, onClose, confirmLabel='Cadastrar', initial={} }) {
  const [form, setForm] = pacState({
    nome: initial.name||'', dob: initial.dob||'', cpf: initial.cpf||'',
    email: initial.email||'', telefone: initial.phone||'',
    cep: initial.cep||'', address: initial.address||''
  });
  const set = k => e => setForm(f => ({ ...f, [k]: e.target.value }));
  return (
    <Modal title={title} onClose={onClose}>
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        <FInput label="Nome" placeholder="Nome completo" value={form.nome} onChange={set('nome')} />
        <div style={{ display:'flex', gap:10 }}>
          <FInput label="Data de nascimento" placeholder="DD/MM/AAAA" value={form.dob} onChange={set('dob')} half />
          <FInput label="CPF" placeholder="000.000.000-00" value={form.cpf} onChange={set('cpf')} half />
        </div>
        <div style={{ display:'flex', gap:10 }}>
          <FInput label="Email" placeholder="email@email.com" value={form.email} onChange={set('email')} half />
          <FInput label="Telefone" placeholder="(00) 00000-0000" value={form.telefone} onChange={set('telefone')} half />
        </div>
        <div style={{ display:'flex', gap:10 }}>
          <FInput label="CEP" placeholder="00000-000" value={form.cep} onChange={set('cep')} style={{ flex:'0 0 120px' }} />
          <FInput label="Endereço Completo" placeholder="Rua, número, complemento, bairro, cidade - UF" value={form.address} onChange={set('address')} />
        </div>
      </div>
      <ModalActions onCancel={onClose} onConfirm={onClose} confirmLabel={confirmLabel} />
    </Modal>
  );
}

/* ── Patient row (list view) ── */
function PatientRow({ p, onView }) {
  return (
    <div style={{ display:'flex', alignItems:'center', padding:'14px 20px', borderBottom:'1px solid #f3f4f6', gap:14 }}>
      <Avatar name={p.name} size={40} />
      <div style={{ width:180, flexShrink:0 }}>
        <div style={{ fontSize:14, fontWeight:600, color:'#111' }}>{p.name}</div>
        <div style={{ display:'flex', alignItems:'center', gap:6, marginTop:3 }}>
          <span style={{ fontSize:12, color:'#6b7280' }}>{p.age} anos</span>
          {p.minor && <Badge variant="menor">Menor de idade</Badge>}
        </div>
      </div>
      <span style={{ fontSize:13, color:'#374151', width:130, flexShrink:0 }}>{p.phone}</span>
      <span style={{ fontSize:13, color:'#374151', flex:1, minWidth:0, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{p.email}</span>
      <div style={{ display:'flex', gap:5, flexShrink:0 }}>
        {p.professionals.map(pr => <Badge key={pr} variant="primary">{pr}</Badge>)}
      </div>
      <div style={{ display:'flex', gap:5, flexShrink:0 }}>
        {p.units.map(u => <Badge key={u} variant="unit">{u}</Badge>)}
      </div>
      <div style={{ display:'flex', gap:6, flexShrink:0 }}>
        <button onClick={() => onView(p)}
          style={{ display:'flex', alignItems:'center', gap:5, padding:'6px 12px', border:'1px solid #d1d5db', borderRadius:6, background:'white', cursor:'pointer', fontSize:12, fontWeight:500, color:'#374151' }}>
          <Icon name="file" size={13} color="#374151" /> Prontuário
        </button>
        <button style={{ display:'flex', alignItems:'center', gap:5, padding:'6px 12px', border:'1px solid #d1d5db', borderRadius:6, background:'white', cursor:'pointer', fontSize:12, fontWeight:500, color:'#374151' }}>
          <Icon name="calendar" size={13} color="#374151" /> Agendar
        </button>
      </div>
    </div>
  );
}

/* ── Patient card (grid view) ── */
function PatientCard({ p, onView }) {
  return (
    <div style={{ background:'white', borderRadius:8, border:'1px solid #e5e7eb', padding:'18px 16px', display:'flex', flexDirection:'column', gap:10 }}>
      <div style={{ display:'flex', alignItems:'center', gap:12 }}>
        <Avatar name={p.name} size={44} />
        <div>
          <div style={{ fontSize:15, fontWeight:700, color:'#111' }}>{p.name}</div>
          <div style={{ fontSize:12, color:'#6b7280', marginTop:2 }}>{p.age} anos</div>
        </div>
      </div>
      <div style={{ fontSize:13, color:'#374151' }}><b style={{ color:'#6b7280' }}>E-mail: </b>{p.email}</div>
      <div style={{ fontSize:13, color:'#374151' }}><b style={{ color:'#6b7280' }}>Telefone: </b>{p.phone}</div>
      <div>
        <div style={{ fontSize:12, color:'#6b7280', marginBottom:5 }}>Profissionais:</div>
        <div style={{ display:'flex', gap:5, flexWrap:'wrap' }}>
          {p.professionals.map(pr => <Badge key={pr} variant="primary">{pr}</Badge>)}
        </div>
      </div>
      <div>
        <div style={{ fontSize:12, color:'#6b7280', marginBottom:5 }}>Unidades:</div>
        <div style={{ display:'flex', gap:5, flexWrap:'wrap' }}>
          {p.units.map(u => <Badge key={u} variant="unit">{u}</Badge>)}
        </div>
      </div>
      <div style={{ display:'flex', gap:8, marginTop:4 }}>
        <button style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center', gap:5, padding:'8px', border:'1px solid #d1d5db', borderRadius:6, background:'white', cursor:'pointer', fontSize:12, fontWeight:500, color:'#374151' }}>
          <Icon name="calendar" size={13} color="#374151" /> Agendar
        </button>
        <button onClick={() => onView(p)}
          style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center', gap:5, padding:'8px', border:'1px solid #d1d5db', borderRadius:6, background:'white', cursor:'pointer', fontSize:12, fontWeight:500, color:'#374151' }}>
          <Icon name="file" size={13} color="#374151" /> Prontuário
        </button>
      </div>
    </div>
  );
}

/* ── Patient Detail ── */
function PatientDetail({ patient, onBack, setModal }) {
  const [tab, setTab] = pacState('info');
  const [showEdit, setShowEdit] = pacState(false);
  const tabs = [
    { id:'info',    label:'Informações' },
    { id:'history', label:'Histórico de Consultas' },
    { id:'records', label:'Prontuários' },
  ];
  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0, background:C.pageBg }}>
      <Topbar title="Pacientes" />
      <div style={{ flex:1, overflowY:'auto', padding:'16px 24px', display:'flex', flexDirection:'column', gap:14 }}>
        {/* Breadcrumb */}
        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
          <button onClick={onBack} style={{ background:'none', border:'none', cursor:'pointer', color:'#6b7280', padding:0 }}>
            <Icon name="back" size={16} color="#6b7280" />
          </button>
          <span onClick={onBack} style={{ fontSize:13, color:C.primary, cursor:'pointer', fontWeight:500 }}>Pacientes</span>
          <span style={{ fontSize:13, color:'#9ca3af' }}>/</span>
          <span style={{ fontSize:13, color:'#374151' }}>{patient.name}</span>
        </div>

        {/* Header card */}
        <Card style={{ padding:'18px 22px', display:'flex', alignItems:'center', gap:16 }}>
          <Avatar name={patient.name} size={54} />
          <div style={{ flex:1 }}>
            <div style={{ fontSize:20, fontWeight:700, color:'#111' }}>{patient.name}</div>
            <div style={{ fontSize:13, color:'#6b7280', marginTop:3 }}>{patient.age} anos</div>
          </div>
          <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
            <button onClick={() => setModal('agendarConsulta')}
              style={{ display:'flex', alignItems:'center', gap:6, padding:'8px 16px', background:C.primary, color:'white', border:'none', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer' }}>
              <Icon name="calendar" size={14} color="white" /> Agendar consulta
            </button>
            <button onClick={() => setShowEdit(true)}
              style={{ display:'flex', alignItems:'center', gap:6, padding:'8px 16px', background:'white', color:'#374151', border:'1px solid #d1d5db', borderRadius:6, fontSize:13, fontWeight:500, cursor:'pointer' }}>
              <Icon name="edit" size={14} color="#374151" /> Editar perfil
            </button>
          </div>
        </Card>

        {/* Tabs */}
        <div style={{ display:'flex', background:'#dbeafe', borderRadius:8, padding:3, gap:2 }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)}
              style={{ flex:1, padding:'8px', borderRadius:6, border:'none', cursor:'pointer', fontSize:13, fontWeight:500,
                background: tab===t.id ? 'white' : 'transparent',
                color: tab===t.id ? '#111' : '#374151',
                boxShadow: tab===t.id ? '0 1px 3px rgba(0,0,0,0.1)' : 'none',
              }}>{t.label}</button>
          ))}
        </div>

        {/* Tab content */}
        {tab === 'info' && (
          <Card style={{ padding:'20px 24px' }}>
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:18 }}>
              <Icon name="usuarios" size={16} color="#374151" />
              <h3 style={{ margin:0, fontSize:15, fontWeight:600, color:'#111' }}>Dados Pessoais</h3>
            </div>
            <div style={{ display:'flex', gap:32, flexWrap:'wrap', marginBottom:24 }}>
              {[
                { label:'Data de Nascimento', val:patient.dob },
                { label:'CPF', val:patient.cpf },
                { label:'E-mail', val:patient.email, icon:'mail' },
                { label:'Telefone', val:patient.phone, icon:'phone' },
                { label:'Endereço', val:patient.address, icon:'pin' },
              ].map(f => (
                <div key={f.label}>
                  <div style={{ fontSize:11, color:'#9ca3af', marginBottom:4 }}>{f.label}</div>
                  <div style={{ fontSize:14, color:'#111', display:'flex', alignItems:'center', gap:5 }}>
                    {f.icon && <Icon name={f.icon} size={13} color="#9ca3af" />}
                    {f.val}
                  </div>
                </div>
              ))}
            </div>
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:14 }}>
              <Icon name="file" size={16} color="#374151" />
              <h3 style={{ margin:0, fontSize:15, fontWeight:600, color:'#111' }}>Documentos</h3>
            </div>
            <div style={{ textAlign:'center', padding:'28px 0' }}>
              <Icon name="download" size={30} color="#d1d5db" />
              <div style={{ fontSize:13, color:'#9ca3af', marginTop:8 }}>Nenhum documento anexado</div>
              <button style={{ marginTop:12, padding:'7px 16px', border:'1px solid #d1d5db', borderRadius:6, background:'white', cursor:'pointer', fontSize:13, color:'#374151', fontWeight:500 }}>+ Anexar documento</button>
            </div>
          </Card>
        )}

        {tab === 'history' && (
          <Card style={{ padding:'20px 24px' }}>
            <h3 style={{ margin:'0 0 16px', fontSize:15, fontWeight:600, color:'#111' }}>Histórico de Atendimentos</h3>
            {patient.appointments.length === 0 ? (
              <div style={{ textAlign:'center', padding:'32px 0', fontSize:15, color:'#374151', fontWeight:500 }}>
                Esse paciente ainda não tem atendimentos
              </div>
            ) : (
              <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
                {patient.appointments.map(a => (
                  <div key={a.id} style={{ display:'flex', alignItems:'center', gap:16, padding:'12px 0', borderBottom:'1px solid #f3f4f6' }}>
                    <div style={{ background:C.primary, borderRadius:8, padding:'8px 10px', textAlign:'center', color:'white', minWidth:60, flexShrink:0 }}>
                      <div style={{ fontSize:11, fontWeight:500 }}>{a.dateLabel}</div>
                      <div style={{ fontSize:15, fontWeight:700 }}>{a.time}</div>
                    </div>
                    <div style={{ flex:1 }}>
                      <div style={{ fontSize:14, fontWeight:600, color:'#111' }}>{a.doctor}</div>
                      <div style={{ fontSize:12, color:'#6b7280' }}>{a.room} • {a.unit}</div>
                    </div>
                    <Badge variant="confirmado">{a.status}</Badge>
                  </div>
                ))}
              </div>
            )}
          </Card>
        )}

        {tab === 'records' && (
          <Card style={{ padding:'20px 24px' }}>
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:14 }}>
              <Icon name="file" size={16} color="#374151" />
              <h3 style={{ margin:0, fontSize:15, fontWeight:600, color:'#111' }}>Documentos</h3>
            </div>
            <div style={{ textAlign:'center', padding:'32px 0' }}>
              <Icon name="file" size={36} color="#d1d5db" />
              <div style={{ fontSize:14, fontWeight:500, color:'#374151', marginTop:10 }}>Nenhum prontuário disponível</div>
              <div style={{ fontSize:12, color:'#9ca3af', marginTop:4 }}>Os prontuários serão exibidos após as consultas serem finalizadas</div>
            </div>
          </Card>
        )}
      </div>
      {showEdit && <ModalPacienteForm title="Editar paciente" onClose={() => setShowEdit(false)} confirmLabel="Salvar alterações" initial={patient} />}
    </div>
  );
}

/* ── Pacientes page ── */
function Pacientes({ setModal }) {
  const [view, setView] = pacState('list');
  const [search, setSearch] = pacState('');
  const [selected, setSelected] = pacState(null);
  const [showNew, setShowNew] = pacState(false);

  if (selected) {
    return <PatientDetail patient={selected} onBack={() => setSelected(null)} setModal={setModal} />;
  }

  const filtered = PATIENTS.filter(p =>
    p.name.toLowerCase().includes(search.toLowerCase()) ||
    p.email.toLowerCase().includes(search.toLowerCase()) ||
    p.phone.includes(search)
  );

  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0, background:C.pageBg }}>
      <Topbar title="Pacientes" />
      <div style={{ flex:1, overflowY:'auto', padding:'16px 24px', display:'flex', flexDirection:'column', gap:14 }}>
        {/* Toolbar */}
        <div style={{ display:'flex', gap:10, alignItems:'center' }}>
          <div style={{ flex:1, position:'relative' }}>
            <div style={{ position:'absolute', left:12, top:'50%', transform:'translateY(-50%)' }}>
              <Icon name="search" size={15} color="#9ca3af" />
            </div>
            <input placeholder="Buscar por nome, e-mail ou telefone..."
              value={search} onChange={e => setSearch(e.target.value)}
              style={{ width:'100%', padding:'9px 12px 9px 36px', border:'1px solid #e5e7eb', borderRadius:8, fontSize:14, background:'white', outline:'none', color:'#111' }} />
          </div>
          <button style={{ display:'flex', alignItems:'center', gap:6, padding:'9px 14px', border:'1px solid #e5e7eb', borderRadius:8, background:'white', cursor:'pointer', fontSize:13, color:'#374151' }}>
            <Icon name="filter" size={14} color="#6b7280" /> Filtros
          </button>
          <button onClick={() => setShowNew(true)}
            style={{ display:'flex', alignItems:'center', gap:6, padding:'9px 16px', background:C.primary, color:'white', border:'none', borderRadius:8, cursor:'pointer', fontSize:13, fontWeight:600 }}>
            + Novo paciente
          </button>
          <button onClick={() => setView('list')}
            style={{ padding:8, border:`1px solid ${view==='list'?C.primary:'#e5e7eb'}`, borderRadius:6, background: view==='list'?'#eff6ff':'white', cursor:'pointer' }}>
            <Icon name="list" size={16} color={view==='list'?C.primary:'#6b7280'} />
          </button>
          <button onClick={() => setView('grid')}
            style={{ padding:8, border:`1px solid ${view==='grid'?C.primary:'#e5e7eb'}`, borderRadius:6, background: view==='grid'?'#eff6ff':'white', cursor:'pointer' }}>
            <Icon name="grid" size={16} color={view==='grid'?C.primary:'#6b7280'} />
          </button>
        </div>

        {/* Content */}
        {filtered.length === 0 ? (
          <Card style={{ padding:'60px 20px', textAlign:'center' }}>
            <div style={{ fontSize:16, fontWeight:500, color:'#374151' }}>Você ainda não tem pacientes cadastrados</div>
          </Card>
        ) : view === 'list' ? (
          <Card>
            {filtered.map(p => <PatientRow key={p.id} p={p} onView={setSelected} />)}
          </Card>
        ) : (
          <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
            {filtered.map(p => <PatientCard key={p.id} p={p} onView={setSelected} />)}
          </div>
        )}
      </div>
      {showNew && <ModalPacienteForm title="Novo paciente" onClose={() => setShowNew(false)} />}
    </div>
  );
}

Object.assign(window, { Pacientes, ModalPacienteForm });
