/*
 This file is part of GNU Taler
 (C) 2022 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/>
 */

import {
  AbsoluteTime,
  Amounts,
  Duration,
  TranslatedString
} from "@gnu-taler/taler-util";
import { useTranslationContext } from "@gnu-taler/web-util/browser";
import { Fragment, VNode, h } from "preact";
import { EnabledBySettings } from "../../components/EnabledBySettings.js";
import { Part } from "../../components/Part.js";
import { PaymentButtons } from "../../components/PaymentButtons.js";
import { ShowFullContractTermPopup } from "../../components/ShowFullContractTermPopup.js";
import { Time } from "../../components/Time.js";
import {
  AgeSign,
  SuccessBox,
  TableWithRoundRows,
  WarningBox,
} from "../../components/styled/index.js";
import { MerchantDetails } from "../../wallet/Transaction.js";
import { State } from "./index.js";

export type PaymentStates =
  | State.Ready
  | State.Confirmed
  | State.NoEnoughBalance;

const inFiveMinutes = AbsoluteTime.addDuration(
  AbsoluteTime.now(),
  Duration.fromSpec({ minutes: 5 }),
);

export function BaseView(state: PaymentStates): VNode {
  const { i18n } = useTranslationContext();


  const willExpireSoon = AbsoluteTime.cmp(state.expiration, inFiveMinutes) === -1;

  // const choices = state.contractTerms.version && state.contractTerms.version === 1 ? state.contractTerms.choices : [];

  return (
    <Fragment>
      <ShowImportantMessage state={state} />

      <section style={{ textAlign: "left" }}>
        <Part
          title={
            state.minimum_age ? (
              <Fragment>
                <i18n.Translate>Purchase</i18n.Translate>
                &nbsp;
                <AgeSign
                  size={20}
                  title={i18n.str`This purchase is age restricted.`}
                >
                  {state.minimum_age}+
                </AgeSign>
              </Fragment>
            ) : (
              <i18n.Translate>Purchase</i18n.Translate>
            )
          }
          text={state.summary as TranslatedString}
          kind="neutral"
        />
        {!state.merchant ? undefined :
          <Part
            title={i18n.str`Merchant`}
            text={<MerchantDetails merchant={state.merchant} />}
            kind="neutral"
          />
        }
        {willExpireSoon && (
          <Part
            title={i18n.str`Expires at`}
            text={<Time timestamp={state.expiration} format="HH:mm" />}
            kind="neutral"
          />
        )}
        {state.status === "confirmed" || state.choices === undefined ? undefined :
          <TableWithRoundRows>
            {state.choices.list.map((entry, idx) => {
              const selected = state.choices!.index === idx;
              const av = Amounts.parseOrThrow(entry.amount);

              return (
                <tr
                  key={idx}
                  onClick={() => state.choices!.select(idx)}
                  style={{ cursor: !selected ? "pointer" : "default" }}
                >
                  <td style={{ borderWidth: selected ? 4 : 1 }}>{av.currency}</td>
                  <td
                    style={{
                      fontSize: "2em",
                      textAlign: "left",
                      borderWidth: selected ? 4 : 1,
                    }}
                  >
                    {Amounts.stringifyValue(av, 2)}
                  </td>
                  <td style={{
                    borderWidth: selected ? 4 : 1,
                    width: "100%",
                    textAlign: "right",
                  }}>{entry.description}</td>

                </tr>
              );
            })}
          </TableWithRoundRows>
        }
      </section>
      <EnabledBySettings name="advancedMode">
        <section style={{ textAlign: "left" }}>
          <ShowFullContractTermPopup
            transactionId={state.transactionId}
          />
        </section>
      </EnabledBySettings>

      <PaymentButtons paymentState={state} />
    </Fragment>
  );
}

function ShowImportantMessage({ state }: { state: PaymentStates }): VNode {
  const { i18n } = useTranslationContext();
  if (state.status === "confirmed") {
    if (state.paid) {
      if (state.message) {
        return (
          <SuccessBox>
            <i18n.Translate>
              Already paid, you are going to be redirected to{" "}
              <a href={state.message}>
                {state.message}
              </a>
            </i18n.Translate>
          </SuccessBox>
        );
      }
      return (
        <SuccessBox>
          <i18n.Translate>Already paid</i18n.Translate>
        </SuccessBox>
      );
    }
    return (
      <WarningBox>
        <i18n.Translate>Already claimed</i18n.Translate>
      </WarningBox>
    );
  }

  return <Fragment />;
}
