import { Form, Link, useLoaderData, useOutletContext } from "@remix-run/react"
import { Rating } from "flowbite-react"
import { useEffect, useState } from "react"
import { ClientOnly } from "remix-utils"

import { getPuertaUrl, getProductos, getProductoUrl } from "~/models/productos.server"
import { getPuertasCarousel } from "~/models/galerias.server"
import { numberWithCommas } from "~/helpers/functions"

import CarouselMasVendidos from "~/components/carouselmasvendidos"
import PersonalizaTuPuerta from "~/components/personalizatupuerta"
import ErrorScreen from "~/components/errorscreen"

import Search from "../../../public/assets/img/btn-buscar.webp"
import Less from "../../../public/assets/img/btn-less.webp"
import More from "../../../public/assets/img/btn-more.webp"
import CartDark from "../../../public/assets/img/cart-icon-dark.webp"
import CheckGreen from "../../../public/assets/img/check-icon-green.webp"

export async function loader({params}) {
    const { productosUrl } = params
    try {
        const [ carousel, productos, puerta, producto ] = await Promise.all( [ getPuertasCarousel(), getProductos(), getPuertaUrl(productosUrl), getProductoUrl(productosUrl) ] )

        if( puerta.data.length === 0 && producto.data.length === 0 ){
            throw new Response( '', {
                status: 404,
                statusText: 'Producto No Encontrado'
            })
        }
        
        loaderData = {
            carousel: carousel.data,
            producto: puerta.data.length === 0 ? producto.data : puerta.data,
            productos: productos.data,
            baseUrl: process.env.WEB_URL
            
        }
        return loaderData
    } catch(error) {
        throw new Response( '', {
            status: 500,
            statusText: 'Error de comunicación, recargue la página'
        })
    }
}

const ProductosDetalle = () => {
    const loadedData = useLoaderData()
    const { carousel, producto, productos, baseUrl } = loadedData

    const id = producto[0].id
    const vc_modelo = typeof producto[0].vc_modelo !== 'undefined' ? producto[0].vc_modelo : producto[0].vc_producto
    const vc_categoria = typeof producto[0].vc_puerta !== 'undefined' ? producto[0].vc_puerta : producto[0].vc_categoria
    const vc_url = producto[0].vc_url
    const f_precio = producto[0].f_precio
    const i_cat = producto[0].i_cat
    const i_descuento = producto[0].i_descuento
    const tx_descripcion = producto[0].tx_descripcion
    const tx_caracteristicas = producto[0].tx_caracteristicas
    const vc_ficha = producto[0].vc_ficha
    const f_alto = producto[0].f_alto
    const f_ancho = producto[0].f_ancho
    const f_peso = producto[0].f_peso
    const vc_imagen = producto[0].vc_imagen

    const [ cantidad, setCantidad ] = useState(1)
    const [ galeria, setGaleria ] = useState(baseUrl+vc_imagen)
    const [ cerraduras, setCerraduras ] = useState({})
    const [ addSmart, setAddSmart ] = useState({})
    const { agregarCarrito, cpEntrega, setCpEntrega } = useOutletContext()

    useEffect( () => {
        const cerraduraFiltro = productos.filter( item => item.i_cat === 8 )
        setCerraduras(cerraduraFiltro)
    }, [])

    const handleAddToCarrito = () => {    
        const productoSeleccionado = {
            precio: f_precio, 
            cat: i_cat, 
            descuento: i_descuento, 
            descripcion: tx_descripcion, 
            id: id, 
            imagen: vc_imagen, 
            modelo: vc_modelo, 
            puerta: vc_categoria, 
            url: vc_url,
            smart: addSmart,
            cantidad
        }
        agregarCarrito(productoSeleccionado)
    }

    const handleApertura = e => {
        const url = vc_url.split("-")
        url.pop()
        window.location.href="/productos/"+url.join("-")+"-"+e
    }    

    const handleAddSmart = (id, vc_producto, vc_imagen, f_precio, tx_descripcion, i_descuento) => {
        const smart = {
            id: id, 
            vc_producto: vc_producto, 
            vc_imagen: vc_imagen, 
            f_precio: f_precio, 
            tx_descripcion: tx_descripcion, 
            i_descuento: i_descuento
        }
        setAddSmart(smart)
    }

    const handleRemoveSmart = () => {
        setAddSmart({})
    }

    const handleCP = e => {
        e.preventDefault()

    }

    return (
        <ClientOnly fallback={'Cargando...'}>
            { () => (
                <div className="bg-eLightGray">

                    <section className="container w-10/12 mx-auto">
                        <div className="lg:flex py-10">
                            <div className="w-full lg:w-5/12 lg:m-5">
                                <div className="bg-white rounded-md p-2 sm:p-20">
                                    <img src={galeria} alt="Galería" />
                                </div>
                                <div className="flex justify-center items-center mt-5">
                                    {/*<div className="w-1/12 flex justify-center items-center">
                                        <img src={Prev} alt="Previo" />
                                    </div>*/}
                                    <div className="w-12/12">
                                        <div className="grid grid-cols-4 gap-2">
                                            {
                                                typeof producto[0] !== 'undefined' ?
                                                    <div  onClick={() => setGaleria(baseUrl+producto[0].vc_imagen)} className="m-3 rounded-md">
                                                        <button className="focus:border-4 focus:border-eBlue rounded-md"><img src={baseUrl+producto[0].vc_imagen} alt="Galeria de productos" /></button>
                                                    </div>
                                                : ""
                                            }
                                            {
                                                typeof producto[1] !== 'undefined' ?
                                                    <div  onClick={() => setGaleria(baseUrl+producto[1].vc_imagen)} className="m-3 rounded-md">
                                                        <button className="focus:border-4 focus:border-eBlue rounded-md"><img src={baseUrl+producto[1].vc_imagen} alt="Galeria de productos" /></button>
                                                    </div>
                                                : ""
                                            }
                                            {
                                                typeof producto[2] !== 'undefined' ?
                                                    <div  onClick={() => setGaleria(baseUrl+producto[2].vc_imagen)} className="m-3 rounded-md">
                                                        <button className="focus:border-4 focus:border-eBlue rounded-md"><img src={baseUrl+producto[2].vc_imagen} alt="Galeria de productos" /></button>
                                                    </div>
                                                : ""
                                            }
                                            {
                                                typeof producto[3] !== 'undefined' ?
                                                    <div  onClick={() => setGaleria(baseUrl+producto[3].vc_imagen)} className="m-3 rounded-md">
                                                        <button className="focus:border-4 focus:border-eBlue rounded-md"><img src={baseUrl+producto[3].vc_imagen} alt="Galeria de productos" /></button>
                                                    </div>
                                                : ""
                                            }
                                            
                                        </div>
                                    </div>
                                    {/*<div className="w-1/12 flex justify-center items-center">
                                        <img src={Next} alt="Siguiente" />
                                    </div>*/}
                                </div>
                            </div>
                            <div className="w-full lg:w-7/12 lg:m-5">
                                <div className="grid grid-cols-1 lg:flex justify-between">
                                    <div className="lg:w-6/12">
                                        <p className="font-MontserratSemiBold text-eGray text-2xl uppercase">
                                            { vc_modelo }
                                        </p>
                                    </div>
                                    <div className="lg:w-6/12 flex flex-col justify-start items-end">
                                        <div className="font-MontserratSemiBold text-eGray text-2xl">
                                            {
                                                i_descuento === 0 
                                                ?
                                                    <p className="w-full text-eBlack text-center font-MontserratSemiBold text-xl mb-2 px-2">${f_precio}</p>
                                                : 
                                                    <>
                                                        <p className="w-full text-eBlack text-center font-MontserratSemiBold text-xs mb-2 px-2 line-through">${f_precio}</p>
                                                        <p className="w-full text-eBlack text-center font-MontserratSemiBold text-xl mb-2 px-2">${ numberWithCommas((f_precio.replace(",","") - (f_precio.replace(",","")*(i_descuento/100))).toFixed(2))}</p>
                                                    </>
                                            }
                                        </div>
                                        {/*<Rating>
                                            <Rating.Star />
                                            <Rating.Star />
                                            <Rating.Star />
                                            <Rating.Star />
                                            <Rating.Star filled={false} />
                                        </Rating>*/}
                                    </div>
                                </div>

                                {/** */}
                                <ul className="mb-0 flex list-none flex-col flex-wrap border-b-0 pl-0 md:flex-row" role="tablist" data-te-nav-ref>
                                    <li role="presentation" className="flex-auto text-center">
                                        <a href="#tabs-home01" className="mt-2 block border-x-0 border-b-2 border-t-0 border-transparent px-7 pb-3.5 pt-4 text-xs font-MontserratRegular uppercase leading-tight text-eGray hover:isolate hover:border-transparent hover:bg-white focus:isolate focus:border-transparent data-[te-nav-active]:bg-white data-[te-nav-active]:text-eGray dark:text-neutral-400 dark:hover:bg-transparent dark:data-[te-nav-active]:border-primary-400 dark:data-[te-nav-active]:text-primary-400" data-te-toggle="pill" data-te-target="#tabs-home01" data-te-nav-active role="tab" aria-controls="tabs-home01" aria-selected="true">descripción</a>
                                    </li>
                                    {
                                        typeof tx_caracteristicas !== 'undefined' && tx_caracteristicas !== "" ?
                                            <li role="presentation" className="flex-auto text-center">
                                                <a href="#tabs-profile01" className="focus:border-transparen mt-2 block border-x-0 border-b-2 border-t-0 border-transparent px-7 pb-3.5 pt-4 text-xs font-MontserratRegular uppercase leading-tight text-eGray hover:isolate hover:border-transparent hover:bg-white focus:isolate data-[te-nav-active]:bg-white data-[te-nav-active]:border-white data-[te-nav-active]:text-eGray dark:text-neutral-400 dark:hover:bg-transparent dark:data-[te-nav-active]:border-primary-400 dark:data-[te-nav-active]:text-primary-400" data-te-toggle="pill" data-te-target="#tabs-profile01" role="tab" aria-controls="tabs-profile01" aria-selected="false">características</a>
                                            </li>
                                        : ""
                                    }
                                    {
                                        typeof vc_ficha !== 'undefined' && vc_ficha !== "" ?
                                            <li className="flex-auto text-center">
                                                <Link to={baseUrl+vc_ficha} target="_blank" className="mt-2 block border-x-0 border-b-2 border-t-0 border-transparent px-7 pb-3.5 pt-4 text-xs font-MontserratRegular uppercase leading-tight text-eGray hover:isolate hover:border-transparent hover:bg-white focus:isolate focus:border-transparent data-[te-nav-active]:bg-white data-[te-nav-active]:border-white data-[te-nav-active]:text-primary dark:text-neutral-400 dark:hover:bg-transparent dark:data-[te-nav-active]:border-primary-400 dark:data-[te-nav-active]:text-eGray-400" >ficha técnica</Link>
                                            </li>
                                        : ""
                                    }
                                </ul>

                                <div className="mb-6">
                                    <div
                                        className="hidden  transition-opacity duration-150 ease-linear data-[te-tab-active]:block data-[te-tab-active]:bg-white px-10 py-5"
                                        id="tabs-home01"
                                        role="tabpanel"
                                        aria-labelledby="tabs-home-tab01"
                                        data-te-tab-active>
                                        <div className="post__content" dangerouslySetInnerHTML={{__html: tx_descripcion}}></div>
                                    </div>
                                    <div
                                        className="hidden opacity-0 transition-opacity duration-150 ease-linear data-[te-tab-active]:block data-[te-tab-active]:bg-white px-10 py-5"
                                        id="tabs-profile01"
                                        role="tabpanel"
                                        aria-labelledby="tabs-profile-tab01">
                                        <div className="post__content" dangerouslySetInnerHTML={{__html: tx_caracteristicas}}></div>
                                        <br />
                                        <p>Alto: {f_alto} cms</p>
                                        <p>Ancho: {f_ancho} cms</p>
                                        <p>Peso: {f_peso} kg</p>
                                    </div>
                                    <div
                                        className="hidden opacity-0 transition-opacity duration-150 ease-linear data-[te-tab-active]:block data-[te-tab-active]:bg-white px-10 py-5"
                                        id="tabs-messages01"
                                        role="tabpanel"
                                        aria-labelledby="tabs-profile-tab01">
                                        <ul>
                                            <li></li>
                                        </ul>
                                    </div>
                                </div>
                                {/** */}

                                <div className="lg:flex gap-4 mt-10">
                                    <div className="lg:w-6/12">
                                        {
                                            vc_url.includes("izquierda") || vc_url.includes("derecha") 
                                            ?
                                                <>
                                                    <label htmlFor="apertura" className="font-MontserratRegular">Dirección de apertura:</label>
                                                    <Form>
                                                        <select 
                                                            id="apertura" 
                                                            onChange={e => handleApertura(e.target.value)}
                                                            value={(vc_url.split("-").pop() === 'izquierda') ? 'izquierda' : 'derecha'} 
                                                            className="mt-5 w-full bg-dropPattern rounded-md border-2 focus:border-eYellow focus:ring-0 border-eGray uppercase content-none select:appearance-none" >
                                                            <option value="">Selecciona</option>
                                                            <option value="izquierda" >Izquierda</option>
                                                            <option value="derecha" >Derecha</option>
                                                        </select>
                                                    </Form>
                                                </>
                                            : ""
                                        }
                                    </div>
                                    <div className="lg:w-6/12 mt-5 lg:mt-0">
                                        <label htmlFor="cobertura" className="font-MontserratRegular">Cobertura de envío:</label>
                                        <Form onSubmit={ e => handleCP(e) } className="mt-5">
                                            <div className="flex "> 
                                                <input 
                                                    id="cobertura" 
                                                    type="text" 
                                                    placeholder="CÓDIGO POSTAL"
                                                    onChange={ e => setCpEntrega(e.target.value) }
                                                    value={cpEntrega}
                                                    className="focus:border-eYellow focus:ring-0 border-2 border-eGray rounded-md w-full" /> 
                                                    {/*className="focus:border-eYellow focus:ring-0 border-2 border-r-0 border-eGray rounded-l-md w-full" />
                                                    <button className="bg-white border-2 border-l-0 border-eGray focus:ring-0 rounded-r-md" type="submit">
                                                    <img src={Search} alt="Buscar" className="p-1" />
                                                    </button>*/}
                                            </div>
                                        </Form>
                                    </div>
                                </div>

                                <hr className="my-10" />

                                { 
                                    typeof tx_caracteristicas !== 'undefined' ??
                                        <p className="uppercase font-MontserratSemiBold text-eBlack ml-5">Agrega una cerradura digital a tu puerta:</p>
                                }

                                {
                                    cerraduras?.length && typeof tx_caracteristicas !== 'undefined'
                                    ?
                                        cerraduras?.map( item => (
                                            producto[0].i_cat === 1 ?
                                                item.id === addSmart.id 
                                                ?
                                                    <div key={item.id} className="lg:flex gap-2 border-eYellow border-2 bg-white py-5 px-3 mt-5">
                                                        <div className="lg:w-2/12 flex justify-center">
                                                            <img src={baseUrl+item.vc_imagen} alt={baseUrl+item.vc_producto} />
                                                        </div>
                                                        <div className="lg:w-7/12 flex flex-col justify-center items-center">
                                                            <p className="text-eGray text-2xl w-full">{item.vc_producto}</p>
                                                            <div className="w-full flex justify-between items-center py-5 lg:py-0">
                                                                <p className="font-MontserratSemiBold text-eGray">+ ${item.f_precio}</p>
                                                                <p><Link to={`/productos/${item.vc_url}`} target="_blank" className="text-eBlue underline">Ver detalles</Link></p>
                                                            </div>
                                                        </div>
                                                        <button 
                                                            onClick={() => handleRemoveSmart()} 
                                                            className="lg:w-3/12 flex justify-center items-center">
                                                            <p className="font-MontserratSemiBold text-eYellow pr-2">Agregado</p>
                                                            <div><img src={Less} alt="Agregado" /></div>
                                                        </button>
                                                    </div>
                                                :
                                                    <div key={item.id} className="lg:flex gap-2 bg-white py-5 px-3 mt-5">
                                                        <div className="lg:w-2/12 flex justify-center">
                                                            <img src={baseUrl+item.vc_imagen} alt={baseUrl+item.vc_producto} />
                                                        </div>
                                                        <div className="lg:w-7/12 flex flex-col justify-center items-center">
                                                            <p className="text-eGray text-2xl w-full">{item.vc_producto}</p>
                                                            <div className="w-full flex justify-between items-center py-5 lg:py-0">
                                                                <p className="font-MontserratSemiBold text-eGray">+ ${item.f_precio}</p>
                                                                <p><Link to={`/productos/${item.vc_url}`} target="_blank" className="text-eBlue underline">Ver detalles</Link></p>
                                                            </div>
                                                        </div>
                                                        <button onClick={() => handleAddSmart(item.id, item.vc_producto, item.vc_imagen, item.f_precio, item.tx_descripcion, item.i_descuento)}  className="lg:w-3/12 flex justify-center items-center">
                                                            <p className="font-MontserratSemiBold text-eGray pr-2">Agregar</p>
                                                            <div><img src={More} alt="Agregar" /></div>
                                                        </button>
                                                    </div>
                                            : ""
                                        ))
                                    : ""
                                }

                                { 
                                    typeof tx_caracteristicas !== 'undefined' ??
                                        <hr className="my-10" />
                                }

                                <div className="lg:flex gap-2 py-5 lg:px-0">
                                    <div className="lg:w-4/12 flex justify-center items-center gap-2">
                                        <img src={CheckGreen} alt="Disponible" />
                                        <p className="font-MontserratRegular text-eGreen">Disponible</p>
                                    </div>
                                    <div className="lg:w-4/12 flex py-5 lg:px-0">
                                        <button onClick={() => setCantidad(cantidad-1)} className="w-full bg-black rounded-l-md">
                                            <p className="font-MontserratBold text-white">-</p>
                                        </button>
                                        <input className="w-full text-center font-MontserratBold" onChange={ () => console.log() } type="text" value={cantidad} />
                                        <button onClick={() => setCantidad(cantidad+1)} className="w-full bg-black rounded-r-md">
                                            <p className="font-MontserratBold text-white">+</p>
                                        </button>
                                    </div>
                                    <div className="lg:w-4/12 py-5 lg:px-0 flex justify-center">
                                        <button onClick={handleAddToCarrito} className="flex gap-1 justify-center items-center bg-eYellow rounded-md py-2 px-4">
                                            <img src={CartDark} alt="Agregar al carrito" />
                                            <p className="font-MontserratRegular text-xs">Agregar al carrito</p>
                                        </button>
                                    </div>
                                </div>

                            </div>
                        </div>
                    </section>

                    <hr className="mb-10" />
                    
                    <section className="containter w-10/12 mx-auto mb-20">
                        <div className="lg:flex justify-between items-center mb-10">
                            <div className="py-2 sm:py-0">
                                <p className="text-2xl text-eBlack font-MontserratRegular">Nuestra puertas más vendidas</p>
                            </div>
                            <div className="py-2 sm:py-0">
                                <Link to="#" className="text-xl text-eBlack font-MontserratRegular underline uppercase">ver todos</Link>
                            </div>
                        </div>

                        <div className="h-[450px]">
                            <CarouselMasVendidos 
                                carousel={carousel}
                                baseUrl={baseUrl}
                            />
                        </div>

                    </section>
                    
                    <PersonalizaTuPuerta />
                    
                </div>
            ) }
        </ClientOnly>
    )
}

export default ProductosDetalle
