/*
 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 {
  HttpStatusCode,
  parsePaytoUri,
  Paytos,
  PaytoType,
  PaytoUri,
  succeedOrThrow,
  TalerMerchantApi,
} from "@gnu-taler/taler-util";
import {
  ButtonBetterBulma,
  LocalNotificationBannerBulma,
  SafeHandlerTemplate,
  useLocalNotificationBetter,
  useTranslationContext
} from "@gnu-taler/web-util/browser";
import { Fragment, h, VNode } from "preact";
import { StateUpdater, useState } from "preact/hooks";
import { useSessionContext } from "../../../../context/session.js";

const TALER_SCREEN_ID = 35;

type Entity = TalerMerchantApi.BankAccountEntry;

interface Props {
  accounts: Entity[];
  onSelect: (e: Entity) => void;
  onCreate: () => void;
}

export function CardTable({ accounts, onCreate, onSelect }: Props): VNode {
  const [rowSelection, rowSelectionHandler] = useState<string[]>([]);

  const { i18n } = useTranslationContext();
  const { state: session, lib } = useSessionContext();
  const [notification, safeFunctionHandler] = useLocalNotificationBetter();

  const remove = safeFunctionHandler(
    lib.instance.deleteBankAccount.bind(lib.instance),
  ).lambda((id: string) => (!session.token ? undefined! : [session.token, id]));
  remove.onFail = (fail) => {
    switch (fail.case) {
      case HttpStatusCode.Unauthorized:
        return i18n.str`Unauthorized`;
      case HttpStatusCode.NotFound:
        return i18n.str`Not found`;
    }
  };
  remove.onSuccess = () => i18n.str`The bank account has been deleted.`;

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

      <div class="card has-table">
        <header class="card-header">
          <p class="card-header-title">
            <span class="icon">
              <i class="mdi mdi-bank" />
            </span>
            <i18n.Translate>Bank accounts</i18n.Translate>
          </p>
          <div class="card-header-icon" aria-label="more options">
            <span
              class="has-tooltip-left"
              data-tooltip={i18n.str`Add new account`}
            >
              <button
                class="button is-info"
                type="button"
                accessKey="+"
                onClick={onCreate}
              >
                <span class="icon is-small">
                  <i class="mdi mdi-plus mdi-36px" />
                </span>
              </button>
            </span>
          </div>
        </header>
        <div class="card-content">
          <div class="b-table has-pagination">
            <div class="table-wrapper has-mobile-cards">
              {accounts.length > 0 ? (
                <Table
                  accounts={accounts}
                  onDelete={remove}
                  onSelect={onSelect}
                  rowSelection={rowSelection}
                  rowSelectionHandler={rowSelectionHandler}
                />
              ) : (
                <EmptyTable />
              )}
            </div>
          </div>
        </div>
      </div>
    </Fragment>
  );
}
interface TableProps {
  rowSelection: string[];
  accounts: Entity[];
  onDelete: SafeHandlerTemplate<[id: string], unknown>;
  onSelect: (e: Entity) => void;
  rowSelectionHandler: StateUpdater<string[]>;
}

function Table({ accounts, onDelete, onSelect }: TableProps): VNode {
  const { i18n } = useTranslationContext();
  const emptyList: Record<
    PaytoType | "unknown",
    { parsed: PaytoUri; acc: Entity }[]
  > = {
    bitcoin: [],
    "x-taler-bank": [],
    iban: [],
    "taler-reserve": [],
    "taler-reserve-http": [],
    unknown: [],
    ethereum: [],
  };

  const accountsByType = accounts.reduce((prev, acc) => {
    const parsed = parsePaytoUri(acc.payto_uri);
    if (!parsed) return prev; //skip
    if (
      parsed.targetType !== "bitcoin" &&
      parsed.targetType !== "taler-reserve" &&
      parsed.targetType !== "taler-reserve-http" &&
      parsed.targetType !== "x-taler-bank" &&
      parsed.targetType !== "iban"
    ) {
      prev["unknown"].push({ parsed, acc });
    } else {
      prev[parsed.targetType].push({ parsed, acc });
    }
    return prev;
  }, emptyList);

  const bitcoinAccounts = accountsByType["bitcoin"];
  const talerbankAccounts = accountsByType["x-taler-bank"];
  const ibanAccounts = accountsByType["iban"];
  const unknownAccounts = accountsByType["unknown"];
  //FIXME: add support for payto://taler-reserve and payto://taler-reserve-http
  //FIXME: this code doesn't adapt well on new payto definitions
  return (
    <Fragment>
      <div class="table-container">
        <table class="table is-fullwidth is-striped is-hoverable is-fullwidth">
          <thead>
            <tr>
              <th>
                <i18n.Translate>Wire method</i18n.Translate>
              </th>
              <th>
                <i18n.Translate>Account</i18n.Translate>
              </th>
              <th>
                <i18n.Translate>Owner's name</i18n.Translate>
              </th>
              <th />
            </tr>
          </thead>
          <tbody>
            {bitcoinAccounts.map(({ parsed, acc }, idx) => {
              return (
                <tr key={idx}>
                  <td
                    onClick={(): void => onSelect(acc)}
                    style={{ cursor: "pointer" }}
                  >
                    Bitcoin
                  </td>
                  <td
                    onClick={(): void => onSelect(acc)}
                    style={{ cursor: "pointer" }}
                  >
                    {
                      succeedOrThrow(Paytos.fromString(acc.payto_uri))
                        .displayName
                    }
                  </td>
                  <td
                    onClick={(): void => onSelect(acc)}
                    style={{ cursor: "pointer" }}
                  >
                    {parsed.params["receiver-name"]}
                  </td>
                  <td class="is-actions-cell right-sticky">
                    <div class="buttons is-right">
                      <ButtonBetterBulma
                        class="button is-danger is-small has-tooltip-left"
                        data-tooltip={i18n.str`Delete selected accounts from the database`}
                        onClick={onDelete.withArgs(acc.h_wire)}
                      >
                        <i18n.Translate>Delete</i18n.Translate>
                      </ButtonBetterBulma>
                    </div>
                  </td>
                </tr>
              );
            })}
            {talerbankAccounts.map(({ parsed, acc }, idx) => {
              return (
                <tr key={idx}>
                  <td
                    onClick={(): void => onSelect(acc)}
                    style={{ cursor: "pointer" }}
                  >
                    x-taler-bank
                  </td>
                  <td
                    onClick={(): void => onSelect(acc)}
                    style={{ cursor: "pointer" }}
                  >
                    {
                      succeedOrThrow(Paytos.fromString(acc.payto_uri))
                        .displayName
                    }
                  </td>
                  <td
                    onClick={(): void => onSelect(acc)}
                    style={{ cursor: "pointer" }}
                  >
                    {parsed.params["receiver-name"]}
                  </td>
                  <td class="is-actions-cell right-sticky">
                    <div class="buttons is-right">
                      <ButtonBetterBulma
                        class="button is-danger is-small has-tooltip-left"
                        data-tooltip={i18n.str`Delete selected accounts from the database`}
                        onClick={onDelete.withArgs(acc.h_wire)}
                      >
                        <i18n.Translate>Delete</i18n.Translate>
                      </ButtonBetterBulma>
                    </div>
                  </td>
                </tr>
              );
            })}
            {ibanAccounts.map(({ parsed, acc }, idx) => {
              return (
                <tr key={idx}>
                  <td
                    onClick={(): void => onSelect(acc)}
                    style={{ cursor: "pointer" }}
                  >
                    IBAN
                  </td>
                  <td
                    onClick={(): void => onSelect(acc)}
                    style={{ cursor: "pointer" }}
                  >
                    {
                      succeedOrThrow(Paytos.fromString(acc.payto_uri))
                        .displayName
                    }
                  </td>
                  <td
                    onClick={(): void => onSelect(acc)}
                    style={{ cursor: "pointer" }}
                  >
                    {parsed.params["receiver-name"]}
                  </td>
                  <td class="is-actions-cell right-sticky">
                    <div class="buttons is-right">
                      <ButtonBetterBulma
                        class="button is-danger is-small has-tooltip-left"
                        data-tooltip={i18n.str`Delete selected accounts from the database`}
                        onClick={onDelete.withArgs(acc.h_wire)}
                      >
                        <i18n.Translate>Delete</i18n.Translate>
                      </ButtonBetterBulma>
                    </div>
                  </td>
                </tr>
              );
            })}
            {unknownAccounts.map(({ parsed, acc }, idx) => {
              return (
                <tr key={idx}>
                  <td
                    onClick={(): void => onSelect(acc)}
                    style={{ cursor: "pointer" }}
                  >
                    {parsed.targetType}
                  </td>
                  <td
                    onClick={(): void => onSelect(acc)}
                    style={{ cursor: "pointer" }}
                  >
                    {
                      succeedOrThrow(Paytos.fromString(acc.payto_uri))
                        .displayName
                    }
                  </td>
                  <td
                    onClick={(): void => onSelect(acc)}
                    style={{ cursor: "pointer" }}
                  >
                    {parsed.params["receiver-name"]}
                  </td>
                  <td class="is-actions-cell right-sticky">
                    <div class="buttons is-right">
                      <ButtonBetterBulma
                        class="button is-danger is-small has-tooltip-left"
                        data-tooltip={i18n.str`Delete selected accounts from the database`}
                        onClick={onDelete.withArgs(acc.h_wire)}
                      >
                        <i18n.Translate>Delete</i18n.Translate>
                      </ButtonBetterBulma>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </Fragment>
  );
}

function EmptyTable(): VNode {
  const { i18n } = useTranslationContext();
  return (
    <div class="content has-text-grey has-text-centered">
      <p>
        <span class="icon is-large">
          <i class="mdi mdi-magnify mdi-48px" />
        </span>
      </p>
      <p>
        <i18n.Translate>
          There are no accounts yet, add more pressing the + sign
        </i18n.Translate>
      </p>
    </div>
  );
}
