import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import 'dayjs/locale/pt-br';
import weekday from 'dayjs/plugin/weekday';
import FormCriarExcecao from '../components/FormCriarExcecao';
import "../components/AgendarConsulta/style/formagendamentos.css";
import "./style/Agendamento.css";
import './style/FilaEspera.css';
import { useAuth } from '../components/utils/AuthProvider';
import API_KEY from '../components/utils/apiKeys';

dayjs.extend(weekday);
dayjs.locale('pt-br');

const ENDPOINT_BASE = "https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/doctor_exceptions"; 

const getDateRange = (date, view) => {
    const startDayjs = dayjs(date);
    let fromDate, toDate, titleRange;

    if (view === 'diario') {
        fromDate = startDayjs.format('YYYY-MM-DD');
        toDate = startDayjs.format('YYYY-MM-DD');
        titleRange = startDayjs.format('DD/MM/YYYY');
    } else if (view === 'semanal') {
 
        let weekStart = startDayjs.startOf('week'); 
        if (weekStart.day() !== 1) { 
             weekStart = startDayjs.weekday(1); 
        }
        
        const weekEnd = weekStart.add(6, 'day');
        
        fromDate = weekStart.format('YYYY-MM-DD');
        toDate = weekEnd.format('YYYY-MM-DD');
        titleRange = `Semana de ${weekStart.format('DD/MM')} a ${weekEnd.format('DD/MM')}`;
        
    } else if (view === 'mensal') {
        const monthStart = startDayjs.startOf('month');
        const monthEnd = startDayjs.endOf('month');
        
        fromDate = monthStart.format('YYYY-MM-DD');
        toDate = monthEnd.format('YYYY-MM-DD');
        titleRange = startDayjs.format('MMMM/YYYY').toUpperCase();
    }
    
    return { fromDate, toDate, titleRange };
};

const ExcecoesDisponibilidade = () => {

    const { getAuthorizationHeader } = useAuth();
    const navigate = useNavigate();
    const [pageNovaExcecao, setPageNovaExcecao] = useState(false);
    const [excecoes, setExcecoes] = useState([]);
    const [loading, setLoading] = useState(false);
    const [showDeleteModal, setShowDeleteModal] = useState(false);
    const [selectedExceptionId, setSelectedExceptionId] = useState(null);
    const [showSuccessModal, setShowSuccessModal] = useState(false);
    const [successMessage, setSuccessMessage] = useState('');
    
    const [filtroMedicoId, setFiltroMedicoId] = useState('');
    const [filtroData, setFiltroData] = useState(dayjs().format('YYYY-MM-DD'));
    const [listaDeMedicos, setListaDeMedicos] = useState([]);
    const [searchTermDoctor, setSearchTermDoctor] = useState('');
    const [filteredDoctors, setFilteredDoctors] = useState([]);
    const [selectedDoctor, setSelectedDoctor] = useState(null);
    
    const [visualizacao, setVisualizacao] = useState('diario');

    const resolveAuthHeader = () => {
        try {
            const h = getAuthorizationHeader();
            return h || '';
        } catch {
            return '';
        }
    }

    const fetchExcecoes = useCallback(async (fromDate, toDate, doctorId) => {
        
        setLoading(true);
        
        let url = `${ENDPOINT_BASE}?select=*`;
        
        if (doctorId) {
            url += `&doctor_id=eq.${doctorId}`; 
        }
        
        url += `&date=gte.${fromDate}&date=lte.${toDate}`;
        
        const myHeaders = new Headers();
        const authHeader = resolveAuthHeader();
        if (authHeader) myHeaders.append("Authorization", authHeader);
        myHeaders.append("Content-Type", "application/json");
        if (API_KEY) myHeaders.append("apikey", API_KEY);

        try {
            const requestOptions = { 
                method: 'GET', 
                headers: myHeaders, 
                redirect: 'follow' 
            };
            
            const response = await fetch(url, requestOptions);
            const result = await response.json(); 
            
            if (response.ok && Array.isArray(result)) {
                setExcecoes(result);
            } else {
                setExcecoes([]);
                console.error("Erro ao listar exceções (Status:", response.status, "):", result);
                alert(`Erro ao carregar lista de exceções. Status: ${response.status}. Detalhes: ${result.message || JSON.stringify(result)}`);
            }
        } catch (error) {
            console.error('Erro na requisição de listagem de exceções:', error);
            setExcecoes([]);
            alert("Erro de comunicação com o servidor ao listar exceções.");
        } finally {
            setLoading(false);
        }
    }, [getAuthorizationHeader]); 

    const { fromDate, toDate, titleRange } = useMemo(() => 
        getDateRange(filtroData, visualizacao), 
        [filtroData, visualizacao]
    );

    useEffect(() => {
        fetchExcecoes(fromDate, toDate, filtroMedicoId);
    }, [fetchExcecoes, filtroMedicoId, fromDate, toDate]);

    useEffect(() => {
        const fetchDoctors = async () => {
            const myHeaders = new Headers();
            const authHeader = resolveAuthHeader();
            if (authHeader) myHeaders.append("Authorization", authHeader);
            if (API_KEY) myHeaders.append("apikey", API_KEY);

            try {
                const response = await fetch('https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/doctors?select=id,full_name', {
                    method: 'GET',
                    headers: myHeaders
                });
                if (response.ok) {
                    const doctors = await response.json();
                    setListaDeMedicos(doctors);
                }
            } catch (error) {
                console.error('Erro ao buscar médicos:', error);
            }
        };
        fetchDoctors();
    }, []);

    const handleSearchDoctors = (term) => {
        setSearchTermDoctor(term);
        if (term.trim() === '') {
            setFilteredDoctors([]);
            return;
        }
        const filtered = listaDeMedicos.filter(doc =>
            doc.full_name.toLowerCase().includes(term.toLowerCase())
        );
        setFilteredDoctors(filtered);
    };

    const limparFiltros = () => {
        setSearchTermDoctor('');
        setFilteredDoctors([]);
        setSelectedDoctor(null);
        setFiltroMedicoId('');
        setFiltroData(dayjs().format('YYYY-MM-DD'));
        setVisualizacao('diario');
    };

    const deleteExcecao = async (id) => {
        const myHeaders = new Headers();
        const authHeader = resolveAuthHeader();
        if (authHeader) myHeaders.append("Authorization", authHeader);
        if (API_KEY) myHeaders.append("apikey", API_KEY);
        myHeaders.append("Content-Type", "application/json");

        try {
            const res = await fetch(`${ENDPOINT_BASE}?id=eq.${id}`, {
                method: 'DELETE',
                headers: myHeaders,
                redirect: 'follow'
            });
            if (res.ok) {
                setExcecoes(prev => prev.filter(x => x.id !== id));
                setShowDeleteModal(false);
                setSuccessMessage('Exceção excluída com sucesso!');
                setShowSuccessModal(true);
            } else {
                const text = await res.text();
                console.error('Erro ao deletar exceção', res.status, text);
                alert(`Erro ao excluir exceção. Status: ${res.status}. ${text}`);
            }
        } catch (err) {
            console.error('Erro na requisição de exclusão:', err);
            alert('Erro ao excluir exceção.');
        }
    }

    const handleCancelForm = (recarregar = false) => {
        setPageNovaExcecao(false);
        if (recarregar) {
            fetchExcecoes(fromDate, toDate, filtroMedicoId);
        }
    }

    if (pageNovaExcecao) {
        return <FormCriarExcecao onCancel={handleCancelForm} doctorID={filtroMedicoId} />;
    }

    return (
        <div>

            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '15px' }}>
                <h1>Gerenciar Exceções de Disponibilidade</h1>
                <button 
                    className="btn-primary" 
                    onClick={() => setPageNovaExcecao(true)}
                    style={{ padding: '10px 20px', fontSize: '14px', whiteSpace: 'nowrap' }} 
                >
                    + Criar Nova Exceção
                </button>
            </div>

            <div className="card p-3 mb-3" style={{ marginTop: '20px' }}>
                <h5 className="mb-3">
                    <i className="bi bi-funnel-fill me-2 text-primary"></i>
                    Filtros
                </h5>
                
                <div className="row g-3 mb-3">
                    <div className="col-md-6">
                        <label className="form-label fw-bold">Buscar Médico</label>
                        <input
                            type="text"
                            className="form-control"
                            placeholder="Digite o nome do médico..."
                            value={searchTermDoctor}
                            onChange={(e) => handleSearchDoctors(e.target.value)}
                        />
                        <small className="text-muted">Filtre as exceções por médico</small>
                        {searchTermDoctor && filteredDoctors.length > 0 && (
                            <div className="list-group mt-2" style={{ maxHeight: '200px', overflowY: 'auto' }}>
                                {filteredDoctors.map((doc) => (
                                    <button
                                        key={doc.id}
                                        className="list-group-item list-group-item-action"
                                        onClick={() => {
                                            setSearchTermDoctor(doc.full_name);
                                            setFilteredDoctors([]);
                                            setSelectedDoctor(doc);
                                            setFiltroMedicoId(doc.id);
                                        }}
                                    >
                                        {doc.full_name}
                                    </button>
                                ))}
                            </div>
                        )}
                    </div>
                    
                    <div className="col-md-6">
                        <label className="form-label fw-bold">Data de Referência</label>
                        <input
                            type="date"
                            className="form-control"
                            value={filtroData}
                            onChange={(e) => setFiltroData(e.target.value)}
                        />
                        <small className="text-muted">Selecione a data base para visualização</small>
                    </div>
                </div>

                <div className="d-flex justify-content-between align-items-center">
                    <div>
                        {selectedDoctor && (
                            <span className="badge bg-primary me-2">
                                <i className="bi bi-person-fill me-1"></i>
                                {selectedDoctor.full_name}
                            </span>
                        )}
                        <div className="contador-pacientes" style={{ display: 'inline-block' }}>
                            {excecoes.length} DE {excecoes.length} EXCEÇÕES ENCONTRADAS
                        </div>
                    </div>
                    
                    <button
                        className="btn btn-outline-secondary btn-sm"
                        onClick={limparFiltros}
                    >
                        <i className="bi bi-arrow-clockwise me-1"></i> Limpar Filtros
                    </button>
                </div>
            </div>

            <div className='atendimento-eprocura'>


                <div className='container-btns-agenda-fila_esepera'>
                    <button
                        className={`btn-agenda ${visualizacao === "diario" ? "opc-agenda-ativo" : ""}`}
                        onClick={() => setVisualizacao('diario')}
                    >
                        Dia
                    </button>
                    <button
                        className={`btn-fila-espera ${visualizacao === "semanal" ? "opc-filaespera-ativo" : ""}`}
                        onClick={() => setVisualizacao('semanal')}
                    >
                        Semana
                    </button>
                    <button
                        className={`btn-fila-espera ${visualizacao === "mensal" ? "opc-filaespera-ativo" : ""}`}
                        onClick={() => setVisualizacao('mensal')}
                    >
                        Mês
                    </button>
                </div>
                

                <section className='calendario-ou-filaespera'>
                    <div className="fila-container">
                        <h2 className="fila-titulo">Exceções em {titleRange} ({excecoes.length})</h2>
                        {loading ? (
                            <p>Carregando exceções...</p>
                        ) : excecoes.length === 0 ? (
                            <p>Nenhuma exceção encontrada para os filtros aplicados.</p>
                        ) : (
                           <table className="fila-tabela">
                                <thead>
                                    <tr>
                                        <th>Médico (ID)</th>
                                        <th>Data</th>
                                        <th>Início</th>
                                        <th>Término</th>
                                        <th>Motivo</th>
                                        <th>Criado por</th>
                                        <th>Ações</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {excecoes.map((exc) => (
                                        <tr key={exc.id}>
                                            <td><p>{exc.doctor_id}</p></td>
                                            <td>{dayjs(exc.date).format('DD/MM/YYYY')}</td>
                                            <td>{exc.start_time ? dayjs(exc.start_time, 'HH:mm:ss').format('HH:mm') : '—'}</td>
                                            <td>{exc.end_time ? dayjs(exc.end_time, 'HH:mm:ss').format('HH:mm') : '—'}</td>
                                            <td><p>{exc.reason}</p></td>
                                            <td>{exc.created_by || '—'}</td>
                                            <td>
                                                <div className="d-flex gap-2">
                                                    <button
                                                        className="btn btn-sm btn-edit"
                                                        onClick={() => {
                                                            setFiltroMedicoId(exc.doctor_id || '');
                                                            setPageNovaExcecao(true);
                                                        }}
                                                    >
                                                        <i className="bi bi-pencil me-1"></i> Editar
                                                    </button>

                                                    <button
                                                        className="btn btn-sm btn-delete"
                                                        onClick={() => {
                                                            setSelectedExceptionId(exc.id);
                                                            setShowDeleteModal(true);
                                                        }}
                                                    >
                                                        <i className="bi bi-trash me-1"></i> Excluir
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        )}
                    </div>
                </section>
            </div>

            {showDeleteModal && (
                <div
                    className="modal fade show delete-modal"
                    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: '#dc3545', color: 'white' }}>
                                <h5 className="modal-title">
                                    Confirmação de Exclusão
                                </h5>
                            </div>

                            <div className="modal-body">
                                <p className="mb-0 fs-5">
                                    Tem certeza que deseja excluir esta exceção?
                                </p>
                            </div>

                            <div className="modal-footer">
                                <button
                                    type="button"
                                    className="btn btn-primary"
                                    onClick={() => setShowDeleteModal(false)}
                                >
                                    Cancelar
                                </button>

                                <button
                                    type="button"
                                    className="btn btn-danger"
                                    onClick={() => deleteExcecao(selectedExceptionId)}
                                >
                                    Excluir
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}


            {showSuccessModal && (
                <div
                    className="modal fade show delete-modal"
                    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: '#1e3a8a', color: 'white' }}>
                                <h5 className="modal-title">
                                    Sucesso
                                </h5>
                            </div>

                            <div className="modal-body">
                                <p className="mb-0 fs-5">
                                    {successMessage}
                                </p>
                            </div>

                            <div className="modal-footer">
                                <button
                                    type="button"
                                    className="btn btn-primary"
                                    onClick={() => setShowSuccessModal(false)}
                                >
                                    OK
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

export default ExcecoesDisponibilidade;