import React, { useState, useEffect } from 'react';
import dayjs from 'dayjs';
import 'dayjs/locale/pt-br';
import { ChevronLeft, ChevronRight, Edit, Trash2, User, Stethoscope } from 'lucide-react';


// Configura o Day.js para usar o idioma português do Brasil
dayjs.locale('pt-br');


const TabelaAgendamentoDia = ({
  agendamentos,
  setDictInfo,
  setShowDeleteModal,
  setSelectedId,
  setShowConfirmModal,
  listaConsultasID,
  coresConsultas
}) => {
  const [currentDate, setCurrentDate] = useState(dayjs());
  const [appointmentsForDay, setAppointmentsForDay] = useState([]);


  useEffect(() => {
    const formattedDate = currentDate.format('YYYY-MM-DD');
    const dailyAppointments = agendamentos[formattedDate] || [];


    const appointmentsComStatusAtualizado = dailyAppointments.map(app => {
      const index = listaConsultasID.indexOf(app.id);
      if (index > -1) {
        return { ...app, status: coresConsultas[index] };
      }
      return app;
    });


    setAppointmentsForDay(appointmentsComStatusAtualizado);
  }, [currentDate, agendamentos, listaConsultasID, coresConsultas]);


  const handlePrevDay = () => {
    setCurrentDate(currentDate.subtract(1, 'day'));
  };


  const handleNextDay = () => {
    setCurrentDate(currentDate.add(1, 'day'));
  };


  const handleEdit = (agendamento) => {
    // Adapte para a sua lógica de edição, talvez abrindo um modal
    console.log("Editar:", agendamento);
    setDictInfo(agendamento);
  };


  const handleDelete = (id) => {
    setSelectedId(id);
    setShowDeleteModal(true);
  };


  // Gera os horários do dia (ex: 08:00 às 18:00)
  const renderTimeSlots = () => {
    const slots = [];
    for (let i = 8; i <= 18; i++) {
      const time = `${i.toString().padStart(2, '0')}:00`;
      const hourlyAppointments = appointmentsForDay.filter(app =>
        dayjs(app.scheduled_at).format('HH:mm') === time
      );


      slots.push(
        <div className="time-slot" key={time}>
          <div className="time-marker">{time}</div>
          <div className="appointments-container">
            {hourlyAppointments.length > 0 ? (
              hourlyAppointments.map(app => (
                <div key={app.id} className="appointment-card" data-status={app.status}>
                  <div className="card-content">
                    <div className="card-line">
                      <Stethoscope size={16} className="card-icon" />
                      <strong>Dr(a):</strong> {app.medico_nome}
                    </div>
                    <div className="card-line">
                      <User size={16} className="card-icon" />
                      <strong>Paciente:</strong> {app.paciente_nome}
                    </div>
                  </div>
                  <div className="card-actions">
                    <button className="btn-card-action" onClick={() => handleEdit(app)}>
                      <Edit size={16} />
                    </button>
                    <button className="btn-card-action btn-delete" onClick={() => handleDelete(app.id)}>
                      <Trash2 size={16} />
                    </button>
                  </div>
                </div>
              ))
            ) : (
              <div className="no-appointment-placeholder"></div>
            )}
          </div>
        </div>
      );
    }
    return slots;
  };


  return (
    <div className="modern-daily-view">
      <div className="calendar-header">
        <button onClick={handlePrevDay} className="btn-nav">
          <ChevronLeft size={24} />
        </button>
        <h2>{currentDate.format('dddd, D [de] MMMM [de] YYYY')}</h2>
        <button onClick={handleNextDay} className="btn-nav">
          <ChevronRight size={24} />
        </button>
      </div>
      <div className="timeline">
        {renderTimeSlots()}
      </div>
    </div>
  );
};


export default TabelaAgendamentoDia;
