/*
 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,
} 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.GroupEntry & WithId;

interface Props {
  onUpdated: () => void;
  onBack?: () => void;
  group: Entity;
}
export function UpdatePage({ group, 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 }[] }>
  >({
    ...group,
    product_map: [],
  });

  // useEffect(() => {
  //   if (!group || !group?.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.GroupAddRequest;
  const update = safeFunctionHandler(
    i18n.str`update product group`,
    lib.instance.updateProductGroup.bind(lib.instance),
    !token ? undefined : [token, group.id, data],
  );
  update.onSuccess = onUpdated;
  update.onFail = (fail) => {
    switch (fail.case) {
      case HttpStatusCode.Unauthorized:
        return i18n.str`Unauthorized`;
      case HttpStatusCode.Conflict:
        return i18n.str`Conflict`;
      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>{group.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="group_name" label={i18n.str`Name`} />
                <Input<Entity>
                  name="description"
                  label={i18n.str`Description`}
                />
                <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>
              </FormProvider>
            </div>
          </div>
        </section>
      </section>
    </div>
  );
}
