/*
 This file is part of GNU Taler
 (C) 2021-2024 Taler Systems S.A.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

/**
 *
 * @author Sebastian Javier Marchano (sebasjm)
 */

import {
  assertUnreachable,
  HttpStatusCode,
  TalerError,
  TalerMerchantApi,
  TranslatedString,
} from "@gnu-taler/taler-util";
import {
  ButtonBetterBulma,
  Loading,
  LocalNotificationBannerBulma,
  useLocalNotificationBetter,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { Fragment, h, VNode } from "preact";
import { useEffect, useState } from "preact/hooks";
import emptyImage from "../../../../assets/empty.png";
import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js";
import { FormProvider } from "../../../../components/form/FormProvider.js";
import { Input } from "../../../../components/form/Input.js";
import { useSessionContext } from "../../../../context/session.js";
import { WithId } from "../../../../declaration.js";
import {
  ProductWithId,
  useInstanceProductsFromIds,
} from "../../../../hooks/product.js";
import { Tooltip } from "../../../../components/Tooltip.js";

const TALER_SCREEN_ID = 39;

type Entity = TalerMerchantApi.CategoryProductList & WithId;

interface Props {
  onUpdated: () => void;
  onBack?: () => void;
  category: Entity;
}
export function UpdatePage({ category, onUpdated, onBack }: Props): VNode {
  const { i18n } = useTranslationContext();
  const {
    state: { token },
    lib,
  } = useSessionContext();
  // FIXME: if the product list is big the will bring a lot of info
  // const inventoryResult = useInstanceProducts();

  // const inventory =
  //   !inventoryResult ||
  //     inventoryResult instanceof TalerError ||
  //     inventoryResult.type === "fail"
  //     ? []
  //     : inventoryResult.body;

  const [state, setState] = useState<
    Partial<Entity & { product_map: { id: string; description: string }[] }>
  >({
    ...category,
    product_map: [],
  });

  useEffect(() => {
    if (!category || !category?.products || !token) return;
    const ps = category.products.map((prod) => {
      return lib.instance
        .getProductDetails(token, String(prod.product_id))
        .then((res) => {
          return res.type === "fail"
            ? undefined
            : {
                id: String(prod.product_id),
                description: res.body.description,
              };
        });
    });
    Promise.all(ps).then((all) => {
      const product_map = all.filter(notEmpty);
      setState({ ...state, product_map });
    });
  }, []);
  const [notification, safeFunctionHandler] = useLocalNotificationBetter();
  const data = state as TalerMerchantApi.CategoryCreateRequest;
  const update = safeFunctionHandler(
    i18n.str`update category`,
    lib.instance.updateCategory.bind(lib.instance),
    !token ? undefined : [token, category.id, data],
  );
  update.onSuccess = onUpdated;
  update.onFail = (fail) => {
    switch (fail.case) {
      case HttpStatusCode.Unauthorized:
        return i18n.str`Unauthorized`;
      case HttpStatusCode.NotFound:
        return i18n.str`Not found`;
      default:
        assertUnreachable(fail);
    }
  };

  return (
    <div>
      <LocalNotificationBannerBulma notification={notification} />

      <section class="section">
        <section class="hero is-hero-bar">
          <div class="hero-body">
            <div class="level">
              <div class="level-left">
                <div class="level-item">
                  <span class="is-size-4">
                    <i18n.Translate>Id:</i18n.Translate>
                    &nbsp;
                    <b>{category.id}</b>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </section>
        <hr />

        <section class="section is-main-section">
          <div class="columns">
            <div class="column is-four-fifths">
              <FormProvider object={state} valueHandler={setState}>
                <Input<Entity>
                  name="name"
                  label={i18n.str`Name`}
                  tooltip={i18n.str`Name of the category`}
                />
                <div class="buttons is-right mt-5">
                  {onBack && (
                    <button class="button" onClick={onBack}>
                      <i18n.Translate>Cancel</i18n.Translate>
                    </button>
                  )}
                  <Tooltip text={i18n.str`Confirm operation`}>
                    <ButtonBetterBulma type="submit" onClick={update}>
                      <i18n.Translate>Confirm</i18n.Translate>
                    </ButtonBetterBulma>
                  </Tooltip>
                </div>
                <ProductListSmall
                  onSelect={() => {}}
                  list={category.products}
                />
              </FormProvider>
            </div>
          </div>
        </section>
      </section>
    </div>
  );
}
function notEmpty<TValue>(value: TValue | null | undefined): value is TValue {
  return value !== null && value !== undefined;
}

function ProductListSmall({
  list,
  onSelect,
}: {
  onSelect: () => void;
  list: TalerMerchantApi.CategoryProductSummary[];
}): VNode {
  const { i18n } = useTranslationContext();
  const result = useInstanceProductsFromIds(list.map((d) => d.product_id));
  if (!result) return <Loading />;
  if (result instanceof TalerError) {
    return <ErrorLoadingMerchant error={result} />;
  }
  if (result.type === "fail") {
    switch (result.case) {
      case HttpStatusCode.NotFound: {
        return <div> not found </div>;
      }
      case HttpStatusCode.Unauthorized: {
        return <div> not authorized </div>;
      }
      default: {
        assertUnreachable(result);
      }
    }
  }
  return (
    <div class="card has-table">
      <header class="card-header">
        <p class="card-header-title">
          <i class="icon mdi mdi-shopping" />
          <i18n.Translate>Products</i18n.Translate>
        </p>
        <div class="card-header-icon" aria-label="more options"></div>
      </header>

      <div class="card-content">
        <div class="b-table has-pagination">
          <div class="table-wrapper has-mobile-cards">
            {result.body.length > 0 ? (
              <Table instances={result.body} onSelect={onSelect} />
            ) : (
              <EmptyTable />
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

interface TableProps {
  instances: ProductWithId[];
  onSelect: (id: Entity) => void;
  onLoadMoreBefore?: () => void;
  onLoadMoreAfter?: () => void;
}
function Table({
  instances,
  onSelect,
  onLoadMoreAfter,
  onLoadMoreBefore,
}: TableProps): VNode {
  const { i18n } = useTranslationContext();
  return (
    <Fragment>
      <table class="table is-fullwidth is-striped is-hoverable is-fullwidth">
        <thead>
          <tr>
            <th>
              <i18n.Translate>Image</i18n.Translate>
            </th>
            <th>
              <i18n.Translate>Name</i18n.Translate>
            </th>
            <th>
              <i18n.Translate>Description</i18n.Translate>
            </th>
          </tr>
        </thead>
        <tbody>
          {instances.map((i) => {
            return (
              <Fragment key={i.id}>
                <tr key="info">
                  <td>
                    <img
                      src={i.image ? i.image : emptyImage}
                      style={{
                        border: "solid black 1px",
                        maxHeight: "2em",
                        width: "auto",
                        height: "auto",
                      }}
                    />
                  </td>
                  <td style={{ cursor: "pointer" }}>{i.product_name}</td>
                  <td style={{ cursor: "pointer" }}>
                    <Tooltip text={i.description as TranslatedString}>
                      {i.description.length > 30
                        ? i.description.substring(0, 30) + "..."
                        : i.description}
                    </Tooltip>
                  </td>
                </tr>
              </Fragment>
            );
          })}
        </tbody>
      </table>
      {onLoadMoreAfter && (
        <Tooltip text={i18n.str`Load more products after the last one`}>
          <button
            type="button"
            class="button is-fullwidth"
            onClick={onLoadMoreAfter}
          >
            <i18n.Translate>Load next page</i18n.Translate>
          </button>
        </Tooltip>
      )}
    </Fragment>
  );
}

function EmptyTable(): VNode {
  const { i18n } = useTranslationContext();
  return (
    <div class="content has-text-grey has-text-centered">
      <p>
        <i18n.Translate>There are no products in this category.</i18n.Translate>
      </p>
    </div>
  );
}
