import { Form, useLoaderData } from "react-router-dom";
import ProductCart from "../../components/product_cart";
import { Product } from "../../models/product";
import MainContentLayout from "../../components/main_content_layout";
import { CartXFill } from "react-bootstrap-icons";
import { Card } from "../../models/card";
import "../../components/stylesheets/shared.css"

function getOrderForm(cards: Array<Card>) {
  if(cards.length > 0) {
    const options = cards.map(card => 
      <option value={card.id}>{card.number}</option>
    );

    return(
      <div className="mx-4 my-1">
        <div className="border-b-2 w-2/6 border-slate-500 my-4">
          <h1 className="text-3xl ">
            Completar pago
          </h1>
        </div>
        <Form method="post" action="/account/orders">
          <div className="my-2 mb-6">
            <select name="card_id" id="card-select">
              {options}
            </select>
          </div>
          <div className="my-2 mb-6">
            <button type="submit" className="text-white button focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 focus:outline-none dark:focus:ring-blue-800">
              Enviar
            </button>
          </div>
        </Form>
      </div>
    );
  }
  else {
    <div className="mx-4 my-1">
      <span className="text-red-600 italic text-lg">
        No tiene ningún método de pago configurado.
      </span>
    </div>
  }
}

function getProducts(product_data: Array<Product>) {
  if(product_data.length > 0) {
    return (product_data.map(product =>
      <ul>
        <li key={product.id}>
          <ProductCart product={product}/>
        </li>
      </ul>
    ));
  }
  else {
    return (
      <div>
        <div className="flex justify-center my-4 w-4/6">
          <CartXFill color="rgb(55 65 81)" size={256}/>
        </div>
        <div className="flex justify-center my-4 w-4/6 text-2xl text-gray-900 my-2">
          Su carrito está vacío, añada algunos productos para empezar a comprar.
        </div>
      </div>
    );
  }
}

export default function Cart() {
  const product_data = useLoaderData()[0] as Array<Product>;
  const cards_data = useLoaderData()[1] as Array<Card>;
  let order_form;
  const products = getProducts(product_data);

  if(product_data.length > 0)
    order_form = getOrderForm(cards_data);
  else
    order_form = null;

  return(
    <>
      <MainContentLayout>
        <div className="grid grid-cols-2">
          <div>
            {products}
          </div>
          {order_form}
        </div>        
      </MainContentLayout>
    </>
  );
}