import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSortUp, faSortDown } from '@fortawesome/free-solid-svg-icons';
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import ReactPaginate from 'react-paginate';
import { Link } from "react-router-dom";
import { toast } from 'react-toastify';

const FuneralTable = () => {
    const [sortConfig, setSortConfig] = useState<{ key: string; direction: string }>({ key: 'id', direction: 'desc' });
    const [funerals, setFunerals] = useState<any>([]);
    const [currentPage, setCurrentPage] = useState(0);
    const itemsPerPage = 10;

    const fetchFunerals = async () => {
        try {
            const response = await axios.get('/admin/funeral/list');
            const sortedData = response.data.sort((a, b) => b.id - a.id);
            setFunerals(sortedData);
        } catch (error) {
            console.error('Error fetching funerals:', error);
        }
    };

    useEffect(() => {
        fetchFunerals();
    }, []);

    const handleSort = (field: string) => {
        setSortConfig({
            key: field,
            direction: sortConfig.key === field && sortConfig.direction === 'asc' ? 'desc' : 'asc'
        });
    };

    const getSortIcon = (field: string) => {
        if (sortConfig.key !== field) return null;
        return sortConfig.direction === 'asc' ? 
            <FontAwesomeIcon icon={faSortUp} style={{ color: '#3c4b64', marginLeft: '5px' }} /> : 
            <FontAwesomeIcon icon={faSortDown} style={{ color: '#3c4b64', marginLeft: '5px' }} />;
    };

    const offset = currentPage * itemsPerPage;
    const paginatedFunerals = funerals.slice(offset, offset + itemsPerPage);

    const sortedFunerals = sortConfig.key ? paginatedFunerals.slice().sort((a, b) => {
        const aValue = a[sortConfig.key];
        const bValue = b[sortConfig.key];
        if (aValue < bValue) return sortConfig.direction === 'asc' ? -1 : 1;
        if (aValue > bValue) return sortConfig.direction === 'asc' ? 1 : -1;
        return 0;
    }) : paginatedFunerals;

    const pageCount = Math.ceil(funerals.length / itemsPerPage);

    const handlePageClick = ({ selected }: any) => {
        setCurrentPage(selected);
    };

    const handleDelete = async (funeral: any) => {
        if (!window.confirm('Êtes-vous sûr de vouloir supprimer cet enterrement ?')) return;

        try {
            const response = await axios.post(`/admin/funeral/${funeral.id}/delete`);
            if (response.data.success) {
                setFunerals(funerals.filter((oldFuneral: any) => funeral.id !== oldFuneral.id));
                toast.success('Enterrement supprimé avec succès'); 
            } else {
                console.error('Error deleting funeral:', response.data.error);
                toast.error('Erreur lors de la suppression de l\'enterrement');
            }
        } catch (error) {
            console.error('Error deleting funeral:', error);
            toast.error('Erreur lors de la suppression de l\'enterrement'); 
        }
    };

    return (
        <>
            <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <h1>Liste des Enterrements</h1>
                {/* <a href="/admin/funeral/new">Créer un nouveau</a> */}
            </div>
            <table className="table">
                <thead>
                    <tr style={{ textAlign: 'center' }}>
                        <th style={{ cursor: 'pointer' }} onClick={() => handleSort('id')}>
                            Id {getSortIcon('id')}
                        </th>
                        <th style={{ cursor: 'pointer' }} onClick={() => handleSort('deadName')}>
                            Nom {getSortIcon('deadName')}
                        </th>
                        <th style={{ cursor: 'pointer' }} onClick={() => handleSort('location.name')}>
                            Lieu {getSortIcon('location.name')}
                        </th>
                        <th style={{ cursor: 'pointer' }} onClick={() => handleSort('dateTime')}>
                            Date {getSortIcon('dateTime')}
                        </th>
                        <th style={{ cursor: 'pointer' }} onClick={() => handleSort('isValidated')}>
                            Validé {getSortIcon('isValidated')}
                        </th>
                        <th style={{ textAlign: 'center' }}>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {Array.isArray(sortedFunerals) && sortedFunerals.map((funeral: any) => (
                        <tr key={funeral.id} style={{ textAlign: 'center' }}>
                            <td>{funeral.id}</td>
                            <td>{funeral.deadName}</td>
                            <td>{funeral.location?.name}</td>
                            <td>{funeral.dateTime ? new Date(funeral.dateTime).toLocaleDateString('fr-FR') : ''}</td>
                            <td>{funeral.isValidated ? 'Oui' : 'Non'}</td>
                            <td>
                                <Link style={{ color: "black", marginRight: "10px" }} className="bg-[#FFDA81] hover:bg-[#F5CD6B] text-xl rounded-lg inline-block font-semibold" to={{ pathname: `/admin/funeral/${funeral.id}/edit` }} state={funeral}>
                                    <FontAwesomeIcon icon={['fas', 'edit']} size="xl" />
                                </Link>
                                <button style={{ marginRight: "10px", border: "none", backgroundColor: "transparent" }} onClick={() => handleDelete(funeral)}>
                                    <FontAwesomeIcon icon={['fas', 'times']} size="xl" color='#AD2E17' />
                                </button>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
            <ReactPaginate
                previousLabel={'Précédent'}
                nextLabel={'Suivant'}
                breakLabel={'...'}
                pageCount={pageCount}
                marginPagesDisplayed={2}
                pageRangeDisplayed={5}
                onPageChange={handlePageClick}
                containerClassName={'pagination'}
                activeClassName={'active'}
                pageClassName="paginationItem"
                pageLinkClassName="paginationLink"
                previousClassName="paginationItem"
                nextClassName="paginationItem"
                breakClassName="paginationItem"
                breakLinkClassName="paginationLink"
                previousLinkClassName="paginationLink"
                nextLinkClassName="paginationLink"
                activeLinkClassName="paginationActive"
            />
            <style>{`
                .pagination {
                    display: flex;
                    list-style-type: none;
                    padding: 0;
                    margin: 20px 0;
                    justify-content: center;
                    user-select: none;
                }
                .paginationItem {
                    margin: 0 5px;
                }
                .paginationLink {
                    display: block;
                    padding: 10px;
                    text-decoration: none;
                    color: black;
                    border: 1px solid #ddd;
                    border-radius: 4px;
                    cursor: pointer;
                    user-select: none;
                }
                .paginationLink:hover {
                    background-color: #f0f0f0;
                    text-decoration: none;
                    color: black;
                }
                .paginationActive {
                    background-color: #000000;
                    color: white;
                    border-color: #000000;
                }
            `}</style>
        </>
    );
}

export default FuneralTable;
