// ============================================================
// Listas do módulo — Histórico, Maquinários, Modelos, Manutenção, Materiais
// ============================================================
function ListShell({ state, empty, children, header }) {
  const { Panel, SkeletonRows, EmptyState } = window
  return (
    <Panel pad={24}>
      {header}
      {state === 'loading' ? <SkeletonRows rows={7} height={26} /> : state === 'empty' ? <EmptyState message={empty} /> : children}
    </Panel>
  )
}

function DateField({ label }) {
  const { Ic, inputStyle } = window
  return (
    <div style={{ position: 'relative', width: 230 }}>
      <input placeholder={label} style={{ ...inputStyle, paddingRight: 40 }} />
      <span style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', opacity: 0.5 }}><Ic name="calendar" size={18} /></span>
    </div>
  )
}

function HistoricoPage({ state, onEdit, isAdmin, onOpenMachinery }) {
  const { Th, Td, Row, TableFrame, Pagination, TypeChip, Ic, Modal, inputStyle, fmtDateBR, fmtNum } = window
  const { HISTORY } = window.MAQ
  const [q, setQ] = React.useState('')
  const [toDelete, setToDelete] = React.useState(null)
  const rows = HISTORY.filter(h => !q || (h.maintenance + h.machinery + h.executor + h.type).toLowerCase().includes(q.toLowerCase()))
  const header = (
    <div style={{ marginBottom: 8 }}>
      <span style={{ display: 'block', fontSize: 13, fontWeight: 500, color: 'var(--color-grayish-dark)', marginBottom: 8 }}>Período</span>
      <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
        <DateField label="Data inicial" /><DateField label="Data final" />
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="Tipo, manutenção, maquinário ou autor" style={{ ...inputStyle, width: 400 }} />
      </div>
    </div>
  )
  return (
    <ListShell state={state} header={header} empty="Nenhuma manutenção registrada.">
      <TableFrame style={{ marginTop: 24 }}>
        <thead><tr><Th>Data</Th><Th>Tipo de manutenção</Th><Th>Manutenção</Th><Th>Maquinário</Th><Th>Modelo</Th><Th>Tipo de maquinário</Th><Th>Km/Horímetro</Th><Th>Autor</Th><Th>Fazenda</Th><Th sortable={false}>Ações</Th></tr></thead>
        <tbody>
          {rows.map((h, i) => (
            <Row key={h.id} i={i}>
              <Td>{fmtDateBR(h.date)}</Td>
              <Td><TypeChip type={h.type} /></Td>
              <Td style={{ maxWidth: 190, whiteSpace: 'normal' }}>{h.maintenance}</Td>
              <Td style={{ maxWidth: 180, whiteSpace: 'normal' }}>{window.MAQ.MACHINERY.some(x => x.name === h.machinery)
                ? <a href="#" onClick={e => { e.preventDefault(); onOpenMachinery && onOpenMachinery(h.machinery) }}>{h.machinery}</a>
                : h.machinery}</Td>
              <Td style={{ maxWidth: 130, whiteSpace: 'normal' }}>{h.model}</Td>
              <Td style={{ maxWidth: 150, whiteSpace: 'normal' }}>{h.machineryType}</Td>
              <Td>{h.mileage == null ? '—' : fmtNum(h.mileage)}</Td>
              <Td>{h.executor}</Td>
              <Td>{h.farm}</Td>
              <Td><span style={{ display: 'inline-flex', gap: 14 }}>
                <Ic name="pencil" size={19} color="var(--color-grayish)" onClick={() => onEdit(h)} />
                {isAdmin && <Ic name="close" size={19} color="var(--color-grayish)" onClick={() => setToDelete(h)} />}</span></Td>
            </Row>
          ))}
        </tbody>
      </TableFrame>
      <Pagination pages={4} page={1} />
      {toDelete && (
        <Modal header="Excluir manutenção" text={`Você tem certeza que deseja excluir a manutenção "${toDelete.maintenance}"? Esta ação não pode ser desfeita.`}
          onClose={() => setToDelete(null)} secondaryLabel="Cancelar" secondaryAction={() => setToDelete(null)}
          primaryLabel="Excluir" primaryType="destructive" primaryAction={() => setToDelete(null)} width={520} />
      )}
    </ListShell>
  )
}

function MaquinariosPage({ state, onOpen }) {
  const { Th, Td, Row, TableFrame, Pagination, SearchInput, fmtNum } = window
  const { MACHINERY } = window.MAQ
  const [q, setQ] = React.useState('')
  const rows = MACHINERY.filter(m => !q || (m.name + m.fleet + m.model).toLowerCase().includes(q.toLowerCase()))
  const header = (
    <div>
      <span style={{ display: 'block', fontSize: 13, fontWeight: 500, color: 'var(--color-grayish-dark)', marginBottom: 8 }}>Pesquisar</span>
      <SearchInput value={q} onChange={setQ} width={400} placeholder="Pesquisar nome ou código do maquinário" />
    </div>
  )
  return (
    <ListShell state={state} header={header} empty="Nenhum maquinário encontrado para a busca.">
      <TableFrame style={{ marginTop: 24 }}>
        <thead><tr><Th sortable={false}>Nome</Th><Th sortable={false}>Tipo de maquinário</Th><Th sortable={false}>Modelo</Th><Th sortable={false}>Km atual</Th><Th sortable={false}>Nº da frota</Th><Th sortable={false}>Fazenda</Th></tr></thead>
        <tbody>
          {rows.map((m, i) => (
            <Row key={m.id} i={i} onClick={() => onOpen(m)}>
              <Td><a href="#" onClick={e => { e.preventDefault(); e.stopPropagation(); onOpen(m) }}>{m.name}</a></Td>
              <Td>{m.type}</Td><Td>{m.model}</Td><Td>{m.mileage == null ? '—' : fmtNum(m.mileage)}</Td><Td>{m.fleet || '—'}</Td><Td>{m.farm}</Td>
            </Row>
          ))}
        </tbody>
      </TableFrame>
      <Pagination pages={4} page={1} />
    </ListShell>
  )
}

function ModelosPage({ state }) {
  const { Th, Td, Row, TableFrame, SearchInput, ActiveChip, Pagination } = window
  const { MODELS, MACHINERY } = window.MAQ
  const [q, setQ] = React.useState('')
  const all = MODELS.map((name, i) => {
    const items = MACHINERY.filter(m => m.model === name)
    const first = items[0] || {}
    return { id: i + 1, name, type: first.type || '—', unit: first.unit || (first.periodic ? 'Dias' : 'Km'), active: true }
  })
  const rows = all.filter(r => !q || (r.name + r.type).toLowerCase().includes(q.toLowerCase()))
  const header = (
    <div>
      <span style={{ display: 'block', fontSize: 13, fontWeight: 500, color: 'var(--color-grayish-dark)', marginBottom: 8 }}>Pesquisar</span>
      <SearchInput value={q} onChange={setQ} width={400} placeholder="Pesquisar tipo ou modelo de maquinário" />
    </div>
  )
  return (
    <ListShell state={state} header={header} empty="Nenhum modelo cadastrado.">
      <TableFrame style={{ marginTop: 24 }}>
        <thead><tr><Th sortable={false}>ID do modelo</Th><Th sortable={false}>Tipo de maquinário</Th><Th sortable={false}>Modelo</Th><Th sortable={false}>Unidade de frequência</Th><Th sortable={false}>Status</Th></tr></thead>
        <tbody>{rows.map((r, i) => (
          <Row key={r.name} i={i}>
            <Td style={{ color: 'var(--color-grayish-dark)' }}>{r.id}</Td><Td>{r.type}</Td><Td style={{ color: 'var(--color-grayish-dark)' }}>{r.name}</Td><Td>{r.unit}</Td>
            <Td><ActiveChip active={r.active} /></Td>
          </Row>))}</tbody>
      </TableFrame>
      <Pagination pages={3} page={1} />
    </ListShell>
  )
}

function ManutencaoPage({ state, onEdit }) {
  const { Th, Td, Row, TableFrame, Pagination, SearchInput, TypeChip, ActiveChip, Ic } = window
  const { MAINTENANCES } = window.MAQ
  const [q, setQ] = React.useState('')
  const rows = MAINTENANCES.filter(m => !q || (m.name + m.model + m.machineryType).toLowerCase().includes(q.toLowerCase()))
  const header = (
    <div>
      <span style={{ display: 'block', fontSize: 13, fontWeight: 500, color: 'var(--color-grayish-dark)', marginBottom: 8 }}>Pesquisar</span>
      <SearchInput value={q} onChange={setQ} width={400} placeholder="Pesquisar nome, tipo de maquinário ou modelo" />
    </div>
  )
  const fmt = (v, unit) => v == null ? '-' : `${v} ${unit}`
  return (
    <ListShell state={state} header={header} empty="Nenhuma manutenção cadastrada.">
      <TableFrame style={{ marginTop: 24 }}>
        <thead><tr><Th sortable={false}>Nome</Th><Th sortable={false}>Tipo de manutenção</Th><Th sortable={false}>Modelo</Th><Th sortable={false}>Tipo de maquinário</Th><Th sortable={false}>Materiais</Th><Th sortable={false}>Frequência de troca</Th><Th sortable={false}>Limite de revisão</Th><Th sortable={false}>Status</Th><Th sortable={false}>Ações</Th></tr></thead>
        <tbody>
          {rows.map((m, i) => (
            <Row key={m.id} i={i}>
              <Td style={{ maxWidth: 120, whiteSpace: 'normal', color: 'var(--color-grayish-dark)' }}>{m.name}</Td>
              <Td><TypeChip type={m.type} /></Td>
              <Td style={{ maxWidth: 130, whiteSpace: 'normal' }}>{m.model}</Td>
              <Td>{m.machineryType}</Td>
              <Td style={{ maxWidth: 320, minWidth: 260, whiteSpace: 'normal', textTransform: 'uppercase', fontSize: 13, letterSpacing: '0.3px' }}>{m.materials.length ? m.materials.map(x => x.name).join(', ') : '-'}</Td>
              <Td>{fmt(m.frequency, m.unit)}</Td>
              <Td>{fmt(m.reviewLimit, m.unit)}</Td>
              <Td><ActiveChip active={m.active} /></Td>
              <Td><Ic name="pencil" size={19} color="var(--color-grayish)" onClick={() => onEdit(m)} /></Td>
            </Row>
          ))}
        </tbody>
      </TableFrame>
      <Pagination pages={2} page={1} />
    </ListShell>
  )
}

function MateriaisPage({ state }) {
  const { Th, Td, Row, TableFrame, Ic, SearchInput, ActiveChip, Pagination } = window
  const { MATERIALS } = window.MAQ
  const [q, setQ] = React.useState('')
  const rows = MATERIALS.filter(m => !q || m.name.toLowerCase().includes(q.toLowerCase()))
  const header = (
    <div>
      <span style={{ display: 'block', fontSize: 13, fontWeight: 500, color: 'var(--color-grayish-dark)', marginBottom: 8 }}>Pesquisar</span>
      <SearchInput value={q} onChange={setQ} width={400} placeholder="Pesquisar nome do material" />
    </div>
  )
  return (
    <ListShell state={state} header={header} empty="Nenhum material cadastrado.">
      <TableFrame style={{ marginTop: 24 }}>
        <thead><tr><Th sortable={false}>Código</Th><Th sortable={false}>Nome</Th><Th sortable={false}>Fabricante</Th><Th sortable={false}>Status</Th><Th sortable={false}>Ações</Th></tr></thead>
        <tbody>{rows.map((m, i) => (
          <Row key={m.id} i={i}>
            <Td style={{ color: 'var(--color-grayish-dark)' }}>{m.code}</Td>
            <Td style={{ color: 'var(--color-grayish-dark)' }}>{m.name}</Td>
            <Td>{m.maker}</Td>
            <Td><ActiveChip active={m.active} /></Td>
            <Td><Ic name="pencil" size={19} color="var(--color-grayish)" /></Td>
          </Row>))}</tbody>
      </TableFrame>
      <Pagination pages={3} page={1} />
    </ListShell>
  )
}

Object.assign(window, { HistoricoPage, MaquinariosPage, ModelosPage, ManutencaoPage, MateriaisPage })
