import React, { useState, useMemo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import API_KEY from '../components/utils/apiKeys.js';
import AgendamentoCadastroManager from './AgendamentoCadastroManager.jsx';
import { GetPatientByID } from '../components/utils/Functions-Endpoints/Patient.js';
import TabelaAgendamentoDia from '../components/AgendarConsulta/TabelaAgendamentoDia';
import TabelaAgendamentoSemana from '../components/AgendarConsulta/TabelaAgendamentoSemana';
import TabelaAgendamentoMes from '../components/AgendarConsulta/TabelaAgendamentoMes';
import FormNovaConsulta from '../components/AgendarConsulta/FormNovaConsulta';
import { GetAllDoctors, GetDoctorByID } from '../components/utils/Functions-Endpoints/Doctor.js';
import { useAuth } from '../components/utils/AuthProvider.js';
import dayjs from 'dayjs';
import 'dayjs/locale/pt-br';
import isBetween from 'dayjs/plugin/isBetween';
import localeData from 'dayjs/plugin/localeData';
import { ChevronLeft, ChevronRight, Edit, Trash2 } from 'lucide-react';
import CalendarComponent from '../components/AgendarConsulta/CalendarComponent.jsx';
import "./style/Agendamento.css";
import './style/FilaEspera.css';
import Spinner from '../components/Spinner.jsx';

dayjs.locale('pt-br');
dayjs.extend(isBetween);
dayjs.extend(localeData);

const Agendamento = ({ setDictInfo }) => {
  const navigate = useNavigate();
  const [listaTodosAgendamentos, setListaTodosAgendamentos] = useState([]);
  const [selectedID, setSelectedId] = useState('0');
  const [filaEsperaData, setFilaEsperaData] = useState([]);
  const [FiladeEspera, setFiladeEspera] = useState(false);
  const [PageNovaConsulta, setPageConsulta] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const { getAuthorizationHeader } = useAuth();
  const [DictAgendamentosOrganizados, setAgendamentosOrganizados] = useState({});
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [ListaDeMedicos, setListaDeMedicos] = useState([]);
  const [FiltredTodosMedicos, setFiltredTodosMedicos] = useState([]);
  const [searchTermDoctor, setSearchTermDoctor] = useState('');
  const [MedicoFiltrado, setMedicoFiltrado] = useState({ id: "vazio" });
  const [cacheAgendamentos, setCacheAgendamentos] = useState([]);
  const [appointmentToEdit, setAppointmentToEdit] = useState(null);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [motivoCancelamento, setMotivoCancelamento] = useState("");
  const [showSpinner, setShowSpinner] = useState(true);
  const [waitlistSearch, setWaitlistSearch] = useState('');
  const [waitSortKey, setWaitSortKey] = useState(null);
  const [waitSortDir, setWaitSortDir] = useState('asc');
  const [waitPage, setWaitPage] = useState(1);
  const [waitPerPage, setWaitPerPage] = useState(10);
  const authHeader = getAuthorizationHeader();
  const cacheMedicos = useMemo(() => ({}), []);
  const cachePacientes = useMemo(() => ({}), []);
  const [currentDate, setCurrentDate] = useState(dayjs());
  const [selectedDay, setSelectedDay] = useState(dayjs());
  const [editingAppointmentId, setEditingAppointmentId] = useState(null);

  const [quickJump, setQuickJump] = useState({
    month: currentDate.month(),
    year: currentDate.year()
  });

  const fetchAppointments = async () => {
    const myHeaders = new Headers();
    myHeaders.append("Authorization", authHeader);
    myHeaders.append("apikey", API_KEY);
    const requestOptions = { method: 'GET', headers: myHeaders, redirect: 'follow' };
    try {
      const res = await fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments?select=*",
        requestOptions
      );
      const data = await res.json();
      setListaTodosAgendamentos(data);
    } catch (err) {
      console.error('Erro ao buscar agendamentos', err);
    }
  };

  const updateAppointmentStatus = async (id, updates) => {
    const myHeaders = new Headers();
    myHeaders.append("Authorization", authHeader);
    myHeaders.append("apikey", API_KEY);
    myHeaders.append("Content-Type", "application/json");
    myHeaders.append("Prefer", "return=representation");
    const requestOptions = { method: 'PATCH', headers: myHeaders, body: JSON.stringify(updates) };

    try {
      const response = await fetch(
        `https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments?id=eq.${id}`,
        requestOptions
      );
      if (response.ok) {
        await fetchAppointments();
        return true;
      } else {
        console.error('Erro ao atualizar agendamento:', await response.text());
        return false;
      }
    } catch (error) {
      console.error('Erro de rede/servidor:', error);
      return false;
    }
  };

  const deleteConsulta = async (id) => {
    setShowSpinner(true);
    const success = await updateAppointmentStatus(id, {
      status: "cancelled",
      cancellation_reason: motivoCancelamento,
      updated_at: new Date().toISOString()
    });
    setShowSpinner(false);
    if (success) {
      setShowDeleteModal(false);
      setMotivoCancelamento("");
      setSelectedId('0');
    } else {
      alert("Falha ao cancelar a consulta.");
    }
  };

  const confirmConsulta = async (id) => {
    setShowSpinner(true);
    const success = await updateAppointmentStatus(id, {
      status: "agendado",
      cancellation_reason: null,
      updated_at: new Date().toISOString()
    });
    setShowSpinner(false);
    if (success) {
      setShowConfirmModal(false);
      setSelectedId('0');
    } else {
      alert("Falha ao reverter o cancelamento.");
    }
  };

  const handleQuickJumpChange = (type, value) => {
    setQuickJump(prev => ({ ...prev, [type]: Number(value) }));
  };

  useEffect(() => {
    setQuickJump({
      month: currentDate.month(),
      year: currentDate.year()
    });
  }, [currentDate]);

  const applyQuickJump = () => {
    let newDate = dayjs().year(quickJump.year).month(quickJump.month).date(1);
    setCurrentDate(newDate);
    setSelectedDay(newDate);
  };

  useEffect(() => {
    if (!listaTodosAgendamentos.length) { setShowSpinner(false); return; }
    setShowSpinner(true);
    const fetchDados = async () => {
      const newDict = {};
      const newFila = [];
      for (const agendamento of listaTodosAgendamentos) {
        if (!agendamento.doctor_id || !agendamento.patient_id) continue;
        if (!cacheMedicos[agendamento.doctor_id]) {
          cacheMedicos[agendamento.doctor_id] =
            (await GetDoctorByID(agendamento.doctor_id, authHeader))[0];
        }
        if (!cachePacientes[agendamento.patient_id]) {
          cachePacientes[agendamento.patient_id] =
            (await GetPatientByID(agendamento.patient_id, authHeader))[0];
        }
        const medico = cacheMedicos[agendamento.doctor_id];
        const paciente = cachePacientes[agendamento.patient_id];

        const agendamentoMelhorado = {
          ...agendamento,
          medico_nome: medico?.full_name,
          paciente_nome: paciente?.full_name,
          paciente_cpf: paciente?.cpf
        };

        if (agendamento.status === "requested") {
          newFila.push({ agendamento: agendamentoMelhorado, Infos: agendamentoMelhorado });
        } else {
          const DiaAgendamento = dayjs(agendamento.scheduled_at).format("YYYY-MM-DD");
          if (newDict[DiaAgendamento]) {
            newDict[DiaAgendamento].push(agendamentoMelhorado);
          } else {
            newDict[DiaAgendamento] = [agendamentoMelhorado];
          }
        }
      }
      for (const key in newDict) {
        newDict[key].sort((a, b) => a.scheduled_at.localeCompare(b.scheduled_at));
      }
      setAgendamentosOrganizados(newDict);
      setFilaEsperaData(newFila);
      setShowSpinner(false);
    };
    fetchDados();
  }, [listaTodosAgendamentos, authHeader, cacheMedicos, cachePacientes]);

  useEffect(() => {
    fetchAppointments();
    GetAllDoctors(authHeader).then(docs =>
      setListaDeMedicos(docs.map(d => ({ nomeMedico: d.full_name, idMedico: d.id })))
    );
  }, [authHeader]);

  const handleSearchMedicos = (term) => { };

  const filaEsperaFiltrada = useMemo(() => {
    if (!waitlistSearch.trim()) return filaEsperaData;
    const term = waitlistSearch.toLowerCase();
    return filaEsperaData.filter(item =>
      (item?.Infos?.paciente_nome?.toLowerCase() || '').includes(term) ||
      (item?.Infos?.paciente_cpf?.toLowerCase() || '').includes(term) ||
      (item?.Infos?.nome_medico?.toLowerCase() || '').includes(term)
    );
  }, [waitlistSearch, filaEsperaData]);

  const applySortingWaitlist = (arr) => {
    if (!Array.isArray(arr) || !waitSortKey) return arr;
    const copy = [...arr];
    if (waitSortKey === 'paciente') {
      copy.sort((a, b) =>
        (a?.Infos?.paciente_nome || '').localeCompare((b?.Infos?.paciente_nome || ''))
      );
    } else if (waitSortKey === 'medico') {
      copy.sort((a, b) =>
        (a?.Infos?.nome_medico || '').localeCompare((b?.Infos?.nome_medico || ''))
      );
    } else if (waitSortKey === 'data') {
      copy.sort((a, b) =>
        new Date(a?.agendamento?.scheduled_at || 0) - new Date(b?.agendamento?.scheduled_at || 0)
      );
    }
    if (waitSortDir === 'desc') copy.reverse();
    return copy;
  };

  const filaEsperaOrdenada = applySortingWaitlist(filaEsperaFiltrada);
  const waitTotalPages = Math.ceil(filaEsperaOrdenada.length / waitPerPage) || 1;
  const waitIndiceInicial = (waitPage - 1) * waitPerPage;
  const waitIndiceFinal = waitIndiceInicial + waitPerPage;
  const filaEsperaPaginada = filaEsperaOrdenada.slice(waitIndiceInicial, waitIndiceFinal);

  const gerarNumerosWaitPages = () => {
    const paginas = [];
    const paginasParaMostrar = 5;
    let inicio = Math.max(1, waitPage - Math.floor(paginasParaMostrar / 2));
    let fim = Math.min(waitTotalPages, inicio + paginasParaMostrar - 1);
    inicio = Math.max(1, fim - paginasParaMostrar + 1);
    for (let i = inicio; i <= fim; i++) { paginas.push(i); }
    return paginas;
  };

  useEffect(() => { setWaitPage(1); }, [waitlistSearch, waitSortKey, waitSortDir]);

  const generateDateGrid = () => {
    const grid = [];
    const startOfMonth = currentDate.startOf('month');
    let currentDay = startOfMonth.subtract(startOfMonth.day(), 'day');
    for (let i = 0; i < 42; i++) {
      grid.push(currentDay);
      currentDay = currentDay.add(1, 'day');
    }
    return grid;
  };

  const dateGrid = useMemo(() => generateDateGrid(), [currentDate]);
  const weekDays = ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'];
  const handleDateClick = (day) => setSelectedDay(day);

  const DeleteModal = () => (
    <div className="modal fade show"
      style={{ display: "block", backgroundColor: "rgba(0,0,0,0.5)" }}
      tabIndex="-1"
    >
      <div className="modal-dialog modal-dialog-centered">
        <div className="modal-content">
          <div className="modal-header" style={{ backgroundColor: '#f8d7da', color: '#721c24' }}>
            <h5 className="modal-title">Confirmação de Cancelamento</h5>
            <button type="button" className="btn-close"
              onClick={() => setShowDeleteModal(false)}
            ></button>
          </div>
          <div className="modal-body">
            <p>Qual o motivo do cancelamento?</p>
            <textarea
              className="form-control"
              rows="3"
              value={motivoCancelamento}
              onChange={(e) => setMotivoCancelamento(e.target.value)}
            ></textarea>
          </div>
          <div className="modal-footer justify-content-center">
            <button
              type="button"
              className="btn btn-secondary"
              onClick={() => { setShowDeleteModal(false); setMotivoCancelamento(""); }}
            >
              Cancelar
            </button>
            <button
              type="button"
              className="btn btn-danger"
              onClick={() => deleteConsulta(selectedID)}
            >
              <Trash2 size={16} className="me-1" /> Excluir
            </button>
          </div>
        </div>
      </div>
    </div>
  );

  const ConfirmEditModal = () => (
    <div className="modal fade show"
      style={{ display: "block", backgroundColor: "rgba(0,0,0,0.5)" }}
      tabIndex="-1"
    >
      <div className="modal-dialog modal-dialog-centered">
        <div className="modal-content">
          <div className="modal-header" style={{ backgroundColor: '#d4edda', color: '#155724' }}>
            <h5 className="modal-title">Confirmação de edição</h5>
            <button type="button" className="btn-close"
              onClick={() => setShowConfirmModal(false)}
            ></button>
          </div>
          <div className="modal-body">
            <p>Tem certeza que deseja retirar o cancelamento?</p>
            <small className="text-muted">Isso reverterá o status do agendamento para Agendado.</small>
          </div>
          <div className="modal-footer justify-content-center">
            <button
              type="button"
              className="btn btn-secondary"
              onClick={() => setShowConfirmModal(false)}
            >
              Cancelar
            </button>
            <button
              type="button"
              className="btn btn-success"
              onClick={() => confirmConsulta(selectedID)}
            >
              <Trash2 size={16} className="me-1" style={{ transform: 'rotate(45deg)' }} /> Confirmar
            </button>
          </div>
        </div>
      </div>
    </div>
  );

  return (
    <div>
      <h1>Agendar nova consulta</h1>

      {!PageNovaConsulta ? (
        <div className='atendimento-eprocura'>
          <div className='container-btns-agenda-fila_esepera'>
            <div className="tabs-agenda-fila">
              <button
                className={`btn-agenda ${!FiladeEspera ? "opc-agenda-ativo" : ""}`}
                onClick={() => { setFiladeEspera(false); setSearchTerm(''); }}
              >
                Agenda
              </button>
              <button
                className={`btn-fila-espera ${FiladeEspera ? "opc-filaespera-ativo" : ""}`}
                onClick={() => { setFiladeEspera(true); setSearchTerm(''); }}
              >
                Fila de espera
              </button>
            </div>

            <div className="btns-gerenciamento-e-consulta">
              <button
                className="btn btn-primary"
                onClick={() => {
                  setPageConsulta(true);
                  setEditingAppointmentId(null);
                  setAppointmentToEdit(null);
                }}
              >
                <i className="bi bi-plus-circle"></i> Adicionar Consulta
              </button>
              <button
                className="manage-button btn"
                onClick={() => navigate("/secretaria/excecoes-disponibilidade")}
              >
                <i className="bi bi-gear-fill me-1"></i> Gerenciar Exceções
              </button>
              <button
                className='manage-button btn'
                onClick={() => navigate('/secretaria/disponibilidade')}
              >
                <i className="bi bi-gear-fill me-1"></i> Mudar Disponibilidade
              </button>
            </div>
          </div>

          <section className='calendario-ou-filaespera'>
            {FiladeEspera === false ? (
              <div className="calendar-wrapper">
                <div className="calendar-info-panel">
                  <div className="info-date-display">
                    <span>{selectedDay.format('MMM')}</span>
                    <strong>{selectedDay.format('DD')}</strong>
                  </div>
                  <div className="info-details">
                    <h3>{selectedDay.format('dddd')}</h3>
                    <p>{selectedDay.format('D [de] MMMM [de] YYYY')}</p>

                    <div
                      className="calendar-legend compact-legend"
                      style={{ marginTop: 6, gap: 4, fontSize: 10 }}
                    >
                      <div className="legend-item" data-status="completed" style={{ padding: '2px 8px' }}>
                        Realizado
                      </div>
                      <div className="legend-item" data-status="confirmed" style={{ padding: '2px 8px' }}>
                        Confirmado
                      </div>
                      <div className="legend-item" data-status="agendado" style={{ padding: '2px 8px' }}>
                        Agendado
                      </div>
                      <div className="legend-item" data-status="cancelled" style={{ padding: '2px 8px' }}>
                        Cancelado
                      </div>
                    </div>

                    <h4 className="subtitle-consultas">
                      Consultas para {selectedDay.format('DD/MM')}
                    </h4>
                  </div>
                  <div className="appointments-list">
                    {showSpinner ? (
                      <Spinner />
                    ) : (() => {
                      const allApps =
                        DictAgendamentosOrganizados[selectedDay.format('YYYY-MM-DD')] || [];
                      const filtered = allApps.filter(app =>
                        !searchTermDoctor
                          ? true
                          : (app.medico_nome || '').toLowerCase()
                              .includes(searchTermDoctor.toLowerCase())
                      );
                      return filtered.length > 0 ? (
                        filtered.map(app => (
                          <div key={app.id} className="appointment-item" data-status={app.status}>
                            <div className="item-time">
                              {dayjs(app.scheduled_at).format('HH:mm')}
                            </div>
                            <div className="item-details">
                              <span>{app.paciente_nome}</span>
                              <small>Dr(a). {app.medico_nome}</small>
                            </div>
                            <div className="appointment-actions">
                              {app.status === 'cancelled' ? (
                                <button
                                  className="btn-action btn-edit"
                                  onClick={() => { setSelectedId(app.id); setShowConfirmModal(true); }}
                                >
                                  <Edit size={16} />
                                </button>
                              ) : (
                                <>
                                  <button
                                    className="btn-action btn-edit"
                                    onClick={() => {
                                      setAppointmentToEdit(app);
                                      setEditingAppointmentId(app.id);
                                      setPageConsulta(true);
                                    }}
                                  >
                                    <Edit size={16} />
                                  </button>
                                  <button
                                    className="btn-action btn-delete"
                                    onClick={() => { setSelectedId(app.id); setShowDeleteModal(true); }}
                                  >
                                    <Trash2 size={16} />
                                  </button>
                                </>
                              )}
                            </div>
                          </div>
                        ))
                      ) : (
                        <div className="no-appointments-info">
                          <p>Nenhuma consulta agendada.</p>
                        </div>
                      );
                    })()}
                  </div>
                </div>

                <div className="calendar-main">
                  <div className="calendar-header-filter">
                    <input
                      type="text"
                      className="form-control"
                      placeholder="Filtrar atendimento do médico"
                      value={searchTermDoctor}
                      onChange={(e) => setSearchTermDoctor(e.target.value)}
                    />
                  </div>

                  <div className="calendar-controls">
                    <div className="date-indicator">
                      <h2>{currentDate.format('MMMM [de] YYYY')}</h2>
                      <div className="quick-jump-controls"
                        style={{ display: 'flex', gap: '5px', marginTop: '10px' }}
                      >
                        <select
                          value={quickJump.month}
                          onChange={(e) => handleQuickJumpChange('month', e.target.value)}
                          className="form-select form-select-sm w-auto"
                        >
                          {dayjs.months().map((month, index) => (
                            <option key={index} value={index}>
                              {month.charAt(0).toUpperCase() + month.slice(1)}
                            </option>
                          ))}
                        </select>
                        <select
                          value={quickJump.year}
                          onChange={(e) => handleQuickJumpChange('year', e.target.value)}
                          className="form-select form-select-sm w-auto"
                        >
                          {Array.from({ length: 11 }, (_, i) => dayjs().year() - 5 + i).map(year => (
                            <option key={year} value={year}>{year}</option>
                          ))}
                        </select>
                        <button
                          className="btn btn-sm btn-outline-primary"
                          onClick={applyQuickJump}
                          disabled={
                            quickJump.month === currentDate.month() &&
                            quickJump.year === currentDate.year()
                          }
                        >
                          Ir
                        </button>
                      </div>
                    </div>

                    <div className="nav-buttons">
                      <button onClick={() => {
                        const newDate = currentDate.subtract(1, 'month');
                        setCurrentDate(newDate);
                        setSelectedDay(newDate);
                      }}>
                        <ChevronLeft size={20} />
                      </button>
                      <button onClick={() => {
                        const today = dayjs();
                        setCurrentDate(today);
                        setSelectedDay(today);
                      }}>
                        Hoje
                      </button>
                      <button onClick={() => {
                        const newDate = currentDate.add(1, 'month');
                        setCurrentDate(newDate);
                        setSelectedDay(newDate);
                      }}>
                        <ChevronRight size={20} />
                      </button>
                    </div>
                  </div>

                  <div className="calendar-grid">
                    {weekDays.map(day => (
                      <div key={day} className="day-header">{day}</div>
                    ))}
                    {dateGrid.map((day, index) => {
                      const dayKey = day.format('YYYY-MM-DD');
                      const appointmentsOnDay = DictAgendamentosOrganizados[dayKey] || [];
                      const filteredAppointments = appointmentsOnDay.filter(app =>
                        !searchTermDoctor
                          ? true
                          : (app.medico_nome || '').toLowerCase()
                              .includes(searchTermDoctor.toLowerCase())
                      );
                      const cellClasses = `day-cell ${
                        day.isSame(currentDate, 'month') ? 'current-month' : 'other-month'
                      } ${day.isSame(dayjs(), 'day') ? 'today' : ''} ${
                        day.isSame(selectedDay, 'day') ? 'selected' : ''
                      }`;
                      return (
                        <div
                          key={index}
                          className={cellClasses}
                          onClick={() => handleDateClick(day)}
                        >
                          <span>{day.format('D')}</span>
                          {filteredAppointments.length > 0 && (
                            <div className="appointments-indicator">
                              {filteredAppointments.length}
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>
            ) : (
              <div className="page-content table-paciente-container">
                <section className="row">
                  <div className="col-12">
                    <div className="card table-paciente-card">
                      <div className="card-header">
                        <h4 className="card-title mb-0">Fila de Espera</h4>
                      </div>
                      <div className="card-body">
                        {/* ... resto da fila de espera igual ao seu código ... */}
                      </div>
                    </div>
                  </div>
                </section>
              </div>
            )}
          </section>
        </div>
           ) : (
        <AgendamentoCadastroManager
          setPageConsulta={setPageConsulta}
          Dict={appointmentToEdit}
          onSaved={() => {
            fetchAppointments();   // recarrega os agendamentos do médico
            setPageConsulta(false);
          }}
        />
      )}

      {showDeleteModal && <DeleteModal />}
      {showConfirmModal && <ConfirmEditModal />}
    </div>
  );
};

export default Agendamento;

