import React, { useState, useEffect } from 'react';
//import PatientList from '../components/patients/PatientList';
//import PatientForm from '../components/patients/PatientForm';
import '../Table.css'


function TablePaciente({ setCurrentPage, setPatientID }) {
  const [pacientes, setPacientes] = useState([]);
  const [search, setSearch] = useState("");

  // Função para excluir paciente
  const deletePatient = async (id) => {
    const requestOptionsDelete = { method: "DELETE", redirect: "follow" };

    if (!window.confirm("Tem certeza que deseja excluir este paciente?")) return;

    await fetch(
      `https://mock.apidog.com/m1/1053378-0-default/pacientes/${id}`,
      requestOptionsDelete
    )
      .then((response) => response.text())
      .then((mensage) => console.log(mensage))
      .catch((error) => console.log("Deu problema", error));
  };

  const onClick = (e, id) => {
    let value = e.target.className;
    console.log(value)

    if(value === 'btn btn-view'){
      setCurrentPage('details-page-paciente')
      setPatientID(id);
    } 
      if(value === 'btn btn-edit'){
      setCurrentPage('edit-page-paciente')
      setPatientID(id);
    
    
      }
     
    
      if (value === "btn btn-delete") {
         deletePatient(id);
         console.log(`Excluir ${id}`);
    

    }
  };

  var requestOptions = {
    method: "GET",
    redirect: "follow",
  };

  useEffect(() => {
    fetch(
      "https://mock.apidog.com/m1/1053378-0-default/pacientes",
      requestOptions
    )
      .then((response) => response.json())
      .then((result) => setPacientes(result["data"]))
      .catch((error) =>
        console.log("Erro para encontrar pacientes no banco de dados", error)
      );
  }, []);

  // Filtrar pacientes pelo campo de pesquisa (nome, cpf, email, telefone)
  const pacientesFiltrados = pacientes.filter((paciente) =>
    `${paciente.nome} ${paciente.cpf} ${paciente.email} ${paciente.telefone}`
      .toLowerCase()
      .includes(search.toLowerCase())
  );

  return (
    <>
      <div className="page-heading">
        <h3>Lista de Pacientes</h3>
      </div>
      <div className="page-content">
        <section className="row">
          <div className="col-12">
            <div className="card">
              {/* Header com título e botão alinhados */}
              <div className="card-header d-flex justify-content-between align-items-center">
                <h4 className="card-title mb-0">Pacientes Cadastrados</h4>
                <button
                  className="btn btn-primary"
                 onClick={() => setCurrentPage("form-layout")}
                >
                  <i className="bi bi-plus-circle"></i> Adicionar Paciente
                </button>
              </div>

              <div className="card-body">
                {/* Barra de pesquisa abaixo do título */}
                <div className="mb-3">
                  <input
                    type="text"
                    placeholder="Pesquisar paciente..."
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    className="form-control"
                  />
                </div>

                <div className="table-responsive">
                  <table className="table table-striped table-hover">
                    <thead>
                      <tr>
                        <th>Nome</th>
                        <th>CPF</th>
                        <th>Email</th>
                        <th>Telefone</th>
                        <th>Opções</th>
                      </tr>
                    </thead>
                    <tbody>
                      {pacientesFiltrados.length > 0 ? (
                        pacientesFiltrados.map((paciente) => (
                          <tr key={paciente.id}>
                            <td>{paciente.nome}</td>
                            <td>{paciente.cpf}</td>
                            <td>{paciente.email}</td>
                            <td>{paciente.telefone}</td>
                            <td>
                              <span
                                className={`badge ${
                                  paciente.ativo === "ativo"
                                    ? "bg-success"
                                    : "bg-danger"
                                }`}
                              >
                                {paciente.ativo}
                              </span>
                            </td>

                            <td>
                               <div className="container">
                                  <button className="btn btn-view" onClick={(e) => onClick(e,paciente.id)}>
                                      <svg viewBox="0 0 24 24" fill="none">
                                          <path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z" stroke="currentColor" stroke-width="1.5" />
                                          <circle cx="12" cy="12" r="3" stroke="currentColor" stroke-width="1.5" />
                                      </svg>
                                      Ver Detalhes
                                  </button>

                                  <button className="btn btn-edit" onClick={(e) => onClick(e,paciente.id)}>
                                      <svg viewBox="0 0 24 24" fill="none">
                                          <path d="M3 21v-3.6l11-11 3.6 3.6-11 11H3z" stroke="currentColor" stroke-width="1.5" />
                                          <path d="M14.5 6.5l3 3" stroke="currentColor" stroke-width="1.5" />
                                      </svg>
                                      Editar
                                  </button>

                                  <button className="btn btn-delete" onClick={(e) => onClick(e,paciente.id)}>
                                      <svg viewBox="0 0 24 24" fill="none">
                                          <path d="M3 6h18" stroke="currentColor" stroke-width="1.5" />
                                          <path d="M8 6V4h8v2" stroke="currentColor" stroke-width="1.5" />
                                          <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" stroke="currentColor" stroke-width="1.5" />
                                          <path d="M10 11v6M14 11v6" stroke="currentColor" stroke-width="1.5" />
                                      </svg>
                                      Excluir
                                  </button>

                                </div>
                            </td>
                          </tr>
                        ))
                      ) : (
                        <tr>
                          <td colSpan="6" className="text-center">
                            Nenhum paciente encontrado.
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </section>
      </div>
    </>
  );
}
export default TablePaciente;