import { Link, useLoaderData } from "@remix-run/react"
import { Dropdown } from 'flowbite-react';
import PersonalizaTuPuerta from "~/components/personalizatupuerta"
import ListadoDeProductos from "~/components/listadodeproductos"
import { useEffect, useState } from "react"
import { getPuertas, getProductos } from "~/models/productos.server";
import Banner from "../../../public/assets/img/cintillo-img.webp"
import Filtros from "~/components/filtros"
import { useOutletContext } from "@remix-run/react";

export function meta() {
    return (
        {
            title: 'Eversafe Productos',
            meta: 'Puertas de seguridad'
        }
    )
}

export async function loader() {
    const [puertasApi, productosApi] = await Promise.all( [ getPuertas(), getProductos() ] )
    loadedData = {
        puertasApi, 
        productosApi
    }
    return loadedData
}

const Seguridad = () => {
    const {seguridad, setSeguridad, acorazada, setAcorazada, balistica, setBalistica, granero, setGranero, deck, setDeck, pisoLaminado, setPisoLaminado, otros, setOtros} = useOutletContext()
    const {puertasApi, productosApi} = useLoaderData()
    const [ puertas, setPuertas ] = useState(puertasApi.data)
    const [ productos, setProductos ] = useState(productosApi.data)
    const [ currentPage, setCurrentPage ] = useState(0)

    useEffect( () => {
        const filtroSeguridad = [...puertasApi.data].filter( value => value.i_cat === 1)
        setPuertas(filtroSeguridad)
        setSeguridad(true)
        setAcorazada(false)
        setBalistica(false)
        setGranero(false)
        setDeck(false)
        setPisoLaminado(false)
        setOtros(false)
    }, [])

    const handleOrder = type => {
        switch( type ) {
            case "nameasc": 
                const strAscending = [...puertasApi.data].sort((a, b) =>
                    a.vc_modelo > b.vc_modelo ? 1 : -1,
                )
                setPuertas(strAscending)
                break
            case "namedesc": 
                const strDescending  = [...puertasApi.data].sort((a, b) =>
                    a.vc_modelo > b.vc_modelo ? -1 : 1,
                )
                setPuertas(strDescending )
                break
            case "priceasc": 
                const numAscending = [...puertasApi.data].sort( (a, b) => Number(a.f_precio.replace(',', '')) - Number(b.f_precio.replace(',', '')) )
                setPuertas(numAscending )
                break
            case "pricedesc": 
                const numDescending = [...puertasApi.data].sort( (a, b) => Number(b.f_precio.replace(',', '')) - Number(a.f_precio.replace(',', '')) )
                setPuertas(numDescending )
                break
        }
    }

    return (
        <>
            <section className="bg-eLightGray">
                <div className="mx-auto w-full lg:flex ">
                    
                    <Filtros 
                        puertasApi={puertasApi} 
                        productosApi={productosApi}
                        puertas={puertas} 
                        setPuertas={setPuertas}
                        seguridad={seguridad} 
                        setSeguridad={setSeguridad}
                        acorazada={acorazada}
                        setAcorazada={setAcorazada}
                        balistica={balistica}
                        setBalistica={setBalistica}
                        granero={granero}
                        setGranero={setGranero}
                        deck={deck}
                        setDeck={setDeck}
                        pisoLaminado={pisoLaminado}
                        setPisoLaminado={setPisoLaminado}
                        otros={otros}
                        setOtros={setOtros}
                    />
                    
                    <div className="w-full lg:w-9/12 p-10">
                        <div className="sm:flex justify-between items-center">
                            <div><p className="text-eGray text-2xl font-MontserratRegular sm:py-5">Mostrando resultados:</p></div>
                            <div id="ordenar">
                                <Dropdown
                                    label="Ordenar por"
                                >
                                    <Dropdown.Item onClick={()=>handleOrder("nameasc")}>
                                        Nombre: A-Z
                                    </Dropdown.Item>
                                    <Dropdown.Item onClick={()=>handleOrder("namedesc")}>
                                        Nombre: Z-A
                                    </Dropdown.Item>
                                    <Dropdown.Item onClick={()=>handleOrder("priceasc")}>
                                        Precio: de menor a mayor
                                    </Dropdown.Item>
                                    <Dropdown.Item onClick={()=>handleOrder("pricedesc")}>
                                        Precio: de mayor a menor
                                    </Dropdown.Item>
                                </Dropdown>
                            </div>
                        </div>

                        <div className="w-full grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-2">
                            
                            <ListadoDeProductos 
                                productos={puertas}
                                currentPage={currentPage}
                                setCurrentPage={setCurrentPage} />

                        </div>

                        <div className="flex items-end justify-end text-center mt-10">
                            <nav aria-label="Page navigation example">
                                <ul className="list-style-none flex">
                                    <li>
                                        <a className="relative block rounded bg-transparent py-1.5 px-3 text-sm text-neutral-600 transition-all duration-300 hover:bg-neutral-100 dark:text-white dark:hover:bg-neutral-700 dark:hover:text-white cursor-pointer" onClick={ () => setCurrentPage(currentPage-1) }>Anterior</a>
                                    </li>

                                    {
                                        (
                                            () => {
                                                const options = [];
                                                for (let i = 0; i < Math.ceil(puertas.length/15); i++) {
                                                    ( currentPage === i ) ?
                                                        options.push(<li key={i} aria-current="page">
                                                            <a className="relative block rounded bg-primary-100 py-1.5 px-3 text-sm font-medium text-primary-700 transition-all duration-300" >
                                                                {i+1}
                                                                <span className="absolute -m-px h-px w-px overflow-hidden whitespace-nowrap border-0 p-0 [clip:rect(0,0,0,0)]">(currentPage)</span>
                                                            </a>
                                                        </li>)
                                                    : options.push(<li key={i}>
                                                        <a className="relative block rounded bg-transparent py-1.5 px-3 text-sm text-neutral-600 transition-all duration-300 hover:bg-neutral-100  dark:text-white dark:hover:bg-neutral-700 dark:hover:text-white cursor-pointer" onClick={ () => setCurrentPage(i) } >{i+1}</a>
                                                    </li>)
                                                }
                                                return options;
                                            }
                                        )()
                                    }          
                                    
                                    <li>
                                        <a className="relative block rounded bg-transparent py-1.5 px-3 text-sm text-neutral-600 transition-all duration-300 hover:bg-neutral-100 dark:text-white dark:hover:bg-neutral-700 dark:hover:text-white cursor-pointer" onClick={ () => setCurrentPage(currentPage+1) } >Siguiente</a>
                                    </li>
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>
            </section>

            <PersonalizaTuPuerta />
        </>
    )
}

export default Seguridad