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

const UserTable = () => {
    const [sortConfig, setSortConfig] = useState<{ key: string; direction: string }>({ key: 'id', direction: 'desc' });
    const [users, setUsers] = useState([]);
    const [currentPage, setCurrentPage] = useState(0);
    const itemsPerPage = 10;

    const fetchUsers = async () => {
        try {
            const response = await axios.get('/admin/user/list');
            setUsers(response.data);
        } catch (error) {
            console.error('Error fetching users:', error);
        }
    };

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

    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 handleDelete = async (id) => {
        Swal.fire({
            title: "Attention",
            html: `Êtes-vous sûr de vouloir supprimer cet utilisateur ?<br>(id: ${id})`,
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Oui",
            cancelButtonText: "Non",
            confirmButtonColor: "#000000",
            cancelButtonColor: "#000000",
            padding: "30px",
            preConfirm: async () => {
                try {
                    const response = await axios.post(`/admin/user/${id}/delete`);
                    if (response.data.success) {
                        setUsers(users.filter(user => user.id !== id));
                        toast.success('Utilisateur ' + id + ' supprimé');
                    } else {
                        console.error('Error deleting user:', response.data.error);
                        toast.error(`Erreur lors de la suppression de l\'utilisateur '${id}' : ${response.data?.error}`);
                    }
                } catch (error) {
                    console.error('Error deleting user:', error);
                    toast.error('Erreur lors de la suppression de l\'utilisateur ' + id + ' : ' + error);
                }
            }
        });
    };

    const offset = currentPage * itemsPerPage;
    const paginatedUsers = users.slice(offset, offset + itemsPerPage);

    const sortedUsers = sortConfig.key ? paginatedUsers.slice().sort((a, b) => {
        const aValue = a ? sortConfig.key.split('.').reduce((o, i) => o ? o[i] : undefined, a) : undefined;
        const bValue = b ? sortConfig.key.split('.').reduce((o, i) => o ? o[i] : undefined, b) : undefined;
        if (aValue < bValue) return sortConfig.direction === 'asc' ? -1 : 1;
        if (aValue > bValue) return sortConfig.direction === 'asc' ? 1 : -1;
        return 0;
    }) : paginatedUsers;

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

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

    const styles = {
        textContainer: {
            whiteSpace: "nowrap",
            overflow: "hidden",
            textOverflow: "ellipsis"
        }
    }

    return (
        <>
            {
                users?.length > 0 ? (
                    <>
                        <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                            <h1>Liste des Utilisateurs</h1>
                        </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('name')}>
                                        Nom {getSortIcon('name')}
                                    </th>
                                    <th style={{ cursor: 'pointer' }} onClick={() => handleSort('email')}>
                                        Email {getSortIcon('email')}
                                    </th>
                                    <th style={{ cursor: 'pointer' }} onClick={() => handleSort('lastLoginAt')}>Dernière connexion</th>
                                    {/* <th style={{ cursor: 'pointer' }} onClick={() => handleSort('subscriptions')}>Participations</th> */}
                                    <th style={{ cursor: 'pointer' }} onClick={() => handleSort('organization')}>Association</th>
                                    <th style={{ textAlign: 'center' }}>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {Array.isArray(sortedUsers) && sortedUsers?.map((user: any) => (
                                    <tr key={user.id} style={{ textAlign: 'center' }}>
                                        <td>{user.id}</td>
                                        <td style={{ ...styles.textContainer, maxWidth: "150px" }}>{user.name}</td>
                                        <td style={{ ...styles.textContainer, maxWidth: "220px" }}>{user.email}</td>
                                        <td style={{ fontSize: "13px" }}>{user.lastLoginAt ? new Date(user.lastLoginAt).toLocaleString() : ''}</td>
                                        {/* <td>{user.subscriptions?.length}</td> */}
                                        <td style={{ ...styles.textContainer, maxWidth: "120px" }}>
                                            {user.organization ? (
                                                <Link to={`/admin/organization/${user.organization.id}/edit`} state={user.organization.id}>
                                                    {user.organization.name}
                                                </Link>
                                            ) : (
                                                ''
                                            )}
                                        </td>
                                        <td style={{ textAlign: 'center' }}>
                                            <Link style={{ color: "black", marginRight: "10px" }} to={`/admin/user/${user.id}/edit`} state={user.id}>
                                                <FontAwesomeIcon icon={['fas', 'edit']} size="lg" />
                                            </Link>
                                            <button
                                                style={{ border: "none", backgroundColor: "transparent" }}
                                                onClick={() => handleDelete(user.id)}
                                            >
                                                <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>
                    </>
                ) : (
                    <div style={{ flex: 1, display: "flex", width: "100%", height: "600px", justifyContent: "center", alignItems: "center" }}>
                        <ClipLoader size={20} color={"#000"} />
                    </div>
                )
            }
        </>
    );
}

export default UserTable;
