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 useGetOrganizations from '../operations/queries/useGetOrganizations';
import { faSortUp, faSortDown } from '@fortawesome/free-solid-svg-icons';

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

    // const fetchOrganizations = async () => {
    //     try {
    //         const response = await axios.get('/admin/organization/list');
    //         setOrganizations(response.data);
    //     } catch (error) {
    //         console.error('Error fetching organizations:', error);
    //     }
    // };

    // useEffect(() => {
    //     fetchOrganizations();
    // }, []);

    const { organizations, manualRefetch, error, isLoading } = useGetOrganizations();

    console.log("organizations", JSON.stringify(organizations?.slice(0, 3), null, 2))

    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 cette association ?<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/organization/${id}/delete`);
                    if (response.data.success) {
                        manualRefetch()
                        toast.success('Association ' + id + ' supprimée avec succès');
                    } else {
                        console.error('Error deleting organization:', response.data.error);
                        toast.error(`Erreur lors de la suppression de l\'association: ${response.data.error}`);
                    }
                } catch (error) {
                    console.error('Error deleting organization:', error);
                    toast.error('Erreur lors de la suppression de l\'association: ' + error?.message);
                }
            }
        });
    };

    const offset = currentPage * itemsPerPage;
    const paginatedOrganizations = organizations?.slice(offset, offset + itemsPerPage);

    const sortedOrganizations = sortConfig.key ? paginatedOrganizations?.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;
    }) : paginatedOrganizations;

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

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

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

    const handleValidate = async (organization) => {
        try {
            const response = await axios.post(`/admin/organization/${organization.id}/validate`);
            console.log("response", response)
            if (response.status === 200) {
                manualRefetch()
                toast.success('Association ' + organization.id + ' validée'); // Affiche un toast de succès
            } else {
                console.error('Error validating organization:', response.data.error);
                toast.error('Erreur lors de la validation de l\'association ' + organization.id + ' : ' + response.data?.error); // Affiche un toast d'erreur
            }
        } catch (error) {
            console.error('Error validating organization:', error);
            toast.error('Erreur lors de la validation de l\'association ' + organization.id + ' : ' + error); // Affiche un toast d'erreur en cas d'erreur
        }
    };

    return (
        <>
            {
                !isLoading ? (
                    <>
                        <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                            <h1>Liste des Associations</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('city')}>Ville</th>
                                    <th style={{ cursor: 'pointer' }} onClick={() => handleSort('phone')}>Téléphone</th>
                                    <th style={{ cursor: 'pointer' }} onClick={() => handleSort('isValidated')}>
                                        Validé {getSortIcon('isValidated')}
                                    </th>
                                    <th style={{ textAlign: 'center' }}>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {Array.isArray(sortedOrganizations) && sortedOrganizations?.map((organization: any) => (
                                    <tr key={organization.id} style={{ textAlign: 'center' }}>
                                        <td>{organization.id}</td>
                                        <td style={{ ...styles.textContainer, maxWidth: "150px" }}>{organization.name}</td>
                                        <td style={{ ...styles.textContainer, maxWidth: "220px" }}>{organization.city}</td>
                                        <td style={{ ...styles.textContainer, maxWidth: "220px" }}>{organization.phone}</td>
                                        <td>{organization.isValidated ? "Oui" : "Non"}</td>
                                        <td style={{ textAlign: 'center' }}>
                                            {/* validation */}
                                            {organization.isValidated != 1 && (
                                                <button style={{ border: "none", backgroundColor: "transparent", marginRight: "10px" }}
                                                    onClick={() => handleValidate(organization)}>
                                                    <FontAwesomeIcon icon={['fas', 'check-square']} size="xl" color='#2CA262' />
                                                </button>
                                            )}
                                            <Link style={{ color: "black", marginRight: "10px" }} to={`/admin/organization/${organization.id}/edit`} state={organization.id}>
                                                <FontAwesomeIcon icon={['fas', 'edit']} size="lg" />
                                            </Link>
                                            <button
                                                style={{ border: "none", backgroundColor: "transparent" }}
                                                onClick={() => handleDelete(organization.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 OrganizationTable;
