import React, { useEffect, useState } from "react";
import { Card } from "./Card/Card";
import { useFetchFlights } from "../../hooks/useFetchFlights";
import { Flight } from "../../Types";
import { useNavigate } from "react-router";
import useAuth from "../../useAuth";
import { useFetchSubscriptions } from "../../hooks/useFetchSubscriptions";

interface Props {
    flights?: Flight[];
}

export const Home: React.FC<Props> = (props) => {
    const urlParams = new URLSearchParams(window.location.search);
    const origin = urlParams.get('origin');
    const initialPage = parseInt(urlParams.get('page') || '1', 10);
    const { flights, count, error, isLoading, fetchData: refreshFlights } = useFetchFlights(origin, initialPage);
    const navigate = useNavigate()

    const [currentPage, setCurrentPage] = useState(initialPage);
    const { loading, isAirline, user, token, isAdmin } = useAuth();
    
    const { subscriptions, loading: subsLoading, fetchData } = useFetchSubscriptions(user, token);

    useEffect(() => {
        const newParams = new URLSearchParams(window.location.search);
        newParams.set('page', currentPage.toString());
        navigate(`?${newParams.toString()}`);
    }, [currentPage, navigate]);

    useEffect(() => {
        if (currentPage > 1 && count == 0) {
            setCurrentPage(currentPage - 1);
        }
    }, [count]);

    const goToPrevPage = () => {
        if (currentPage > 1) {
            setCurrentPage(currentPage - 1);
        }
    };

    const goToNextPage = () => {
        setCurrentPage(currentPage + 1);
    };

    const checkMaxPage = () => {
        return currentPage * 8 >= count ? false : true
    }

    const checkMinPage = () => {
        return currentPage > 1 ? true : false
    }

    if (loading || isLoading || subsLoading) {
        return <div>Loading...</div>;
    }

    let columns = flights.length >= 4 ? 4 : flights.length
    
    return (
        <div className="Box">
            {isAirline ? <button name="CreateFlight" onClick={() => { navigate("/create-flight") }}>Create flight</button> : <></>}
            {isAdmin ? <button onClick={() => { navigate("/create-airline") }}>Create airline user</button> : <></>}
            <h2>Flights</h2>
            <div className="Items" style={{ gridTemplateColumns: `repeat(${columns}, minmax(80px, 250px))` }}>
                {(props.flights ? props.flights : flights).map((f) => {
                    return <Card key={f.id} flight={f} user={user} 
                    subscribed={subscriptions.some((i => i.flight_id === f.id))} 
                    refresh={fetchData} refreshFlights={refreshFlights} isAirline={isAirline} isAdmin={isAdmin} />;
                })}
                {error ? <div className="Disconnected">{error}</div> : <></>}
            </div>
            <div>
                {checkMinPage() && <button onClick={goToPrevPage}>Prev</button>}
                <span> Page {currentPage} </span>
                {checkMaxPage() && <button onClick={goToNextPage}>Next</button>}
            </div>
        </div>
    );
};
