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

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

    // const fetchLocations = async () => {
    //     try {
    //         const response = await axios.get('/admin/location/list');
    //         setLocations(response.data);
    //     } catch (error) {
    //         console.error('Error fetching locations:', error);
    //     }
    // };

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

    const { locations, manualRefetch, error, isLoading } = useGetLocations();

    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 (selectedLocation) => {
        Swal.fire({
            title: "Attention",
            html: `Êtes-vous sûr de vouloir supprimer ce lieu ?<br>(id: ${selectedLocation.id})<br>Cela va supprimer toutes les janazas associées (${selectedLocation.janazas?.length})`,
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Oui",
            cancelButtonText: "Non",
            confirmButtonColor: "#000000",
            cancelButtonColor: "#000000",
            padding: "30px",
            preConfirm: async () => {
                try {
                    const response = await axios.post(`/admin/location/${selectedLocation.id}/delete`);
                    if (response.data.success) {
                        manualRefetch()
                        toast.success('Lieu ' + selectedLocation.id + ' supprimé');
                    } else {
                        console.error('Error deleting location:', response.data.error);
                        toast.error(`Erreur lors de la suppression du lieu ${selectedLocation.id} : ${response.data?.error}`);
                    }
                } catch (error) {
                    console.error('Error deleting location:', error);
                    toast.error('Erreur lors de la suppression du lieu ' + selectedLocation.id + ' : ' + error);
                }
            }
        });
    };

    const offset = currentPage * itemsPerPage;
    const paginatedLocations = locations?.slice(offset, offset + itemsPerPage);

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


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

    const locationTypes = [
        { label: "Mosquée", value: "mosque" },
        { label: "Cimetière", value: "cemetery" },
        { label: "Funérarium", value: "funeral_home" },
        { label: "Salle de prière", value: "prayer_room" },
        { label: "Hopital", value: "hospital" },
    ]

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

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



    return (
        <>
            {
                !isLoading ? (
                    <>
                        <div style={{ flex: 1, display: "flex", width: "100%", justifyContent: "space-between" }}>
                            <h1>Liste des Lieux</h1>
                            <Link to={{ pathname: `/admin/location/new` }} style={{ color: "black", marginRight: "40px", marginBottom: "30px", borderRadius: "99px", padding: "10px", border: "2px solid black", alignSelf: "end", }}>
                                <FontAwesomeIcon icon={['fas', 'plus']} size="xl" />
                            </Link>
                        </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('type')}>Type</th>
                                    <th style={{ cursor: 'pointer' }} onClick={() => handleSort('department.name')}>Département</th>
                                    <th style={{ textAlign: 'center' }}>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {Array.isArray(sortedLocations) && sortedLocations?.map((location: any) => (
                                    <tr key={location.id} style={{ textAlign: 'center' }}>
                                        <td>{location.id}</td>
                                        <td style={{ ...styles.textContainer, maxWidth: "150px" }}>{location.name}</td>
                                        <td style={{ ...styles.textContainer, maxWidth: "150px" }}>{locationTypes.find((locationType) => locationType.value === location.type)?.label ?? location.type}</td>
                                        <td style={{ ...styles.textContainer, maxWidth: "150px" }}>{location.department?.name}</td>
                                        <td style={{ textAlign: 'center' }}>
                                            <Link style={{ color: "black", marginRight: "10px" }} to={`/admin/location/${location.id}/edit`} state={location.id}>
                                                <FontAwesomeIcon icon={['fas', 'edit']} size="lg" />
                                            </Link>
                                            <button
                                                style={{ border: "none", backgroundColor: "transparent" }}
                                                onClick={() => handleDelete(location)}
                                            >
                                                <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 LocationTable;
