/*
 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 {
  BankAccountEntry,
  ExpectedTransferEntry,
  HttpStatusCode,
  TalerError,
  TransferDetails,
  assertUnreachable,
} from "@gnu-taler/taler-util";
import {
  PaginatedResult,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { Fragment, VNode, h } from "preact";
import { StateUpdater, useState } from "preact/hooks";
import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js";
import { Loading } from "../../../../components/exception/loading.js";
import { FormProvider } from "../../../../components/form/FormProvider.js";
import { InputSelector } from "../../../../components/form/InputSelector.js";
import { InputToggle } from "../../../../components/form/InputToggle.js";
import { useInstanceBankAccounts } from "../../../../hooks/bank.js";
import {
  useInstanceConfirmedTransfers,
  useInstanceIncomingTransfers,
} from "../../../../hooks/transfer.js";
import { LoginPage } from "../../../login/index.js";
import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js";
import { ListPage } from "./ListPage.js";

interface Props {
  onTransferDetails: (id: number) => void;
}
interface Form {
  expected?: boolean;
  confirmed?: boolean;
  verified?: boolean;
  payto_uri?: string;
}

export default function ListTransfer({ onTransferDetails }: Props): VNode {
  const result = useInstanceBankAccounts();

  if (!result) {
    return <Loading />;
  }
  if (result instanceof TalerError || result.type === "fail") {
    return (
      <ListTransferWithBank
        bankAccounts={[]}
        onTransferDetails={onTransferDetails}
      />
    );
  }
  return (
    <ListTransferWithBank
      bankAccounts={result.body.accounts}
      onTransferDetails={onTransferDetails}
    />
  );
}

function ListTransferWithBank({
  bankAccounts,
  onTransferDetails,
}: {
  onTransferDetails: (id: number) => void;
  bankAccounts: BankAccountEntry[];
}): VNode {
  const [position, setPosition] = useState<string | undefined>(undefined);
  const accounts = bankAccounts.map((b) => b.payto_uri);
  const [form, setForm] = useState<Form>({
    payto_uri: accounts.length > 0 ? accounts[0] : "",
  });

  let incoming: PaginatedResult<ExpectedTransferEntry[]>;
  {
    const result = useInstanceIncomingTransfers(
      {
        position,
        payto_uri: form.payto_uri === "" ? undefined : form.payto_uri,
        verified: form.verified,
        confirmed: false,
      },
      (id) => setPosition(id),
    );

    if (!result) return <Loading />;
    if (result instanceof TalerError) {
      return <ErrorLoadingMerchant error={result} />;
    }
    if (result.type === "fail") {
      switch (result.case) {
        case HttpStatusCode.Unauthorized: {
          return <LoginPage focus />;
        }
        case HttpStatusCode.NotFound: {
          return <NotFoundPageOrAdminCreate />;
        }
        default: {
          assertUnreachable(result);
        }
      }
    }
    incoming = result;
  }
  let confirmed: PaginatedResult<TransferDetails[]>;
  {
    const result = useInstanceConfirmedTransfers(
      {
        position,
        payto_uri: form.payto_uri === "" ? undefined : form.payto_uri,
        // expected: form.expected,
        verified: form.verified,
      },
      (id) => setPosition(id),
    );

    if (!result) return <Loading />;
    if (result instanceof TalerError) {
      return <ErrorLoadingMerchant error={result} />;
    }
    if (result.type === "fail") {
      switch (result.case) {
        case HttpStatusCode.Unauthorized: {
          return <LoginPage focus />;
        }
        case HttpStatusCode.NotFound: {
          return <NotFoundPageOrAdminCreate />;
        }
        default: {
          assertUnreachable(result);
        }
      }
    }
    confirmed = result;
  }

  return (
    <ListTransferInternal
      accounts={accounts}
      onTransferDetails={onTransferDetails}
      form={form}
      setForm={setForm}
      incomings={incoming}
      transfers={confirmed}
      onSelect={() => undefined}
    />
  );
}

function ListTransferInternal({
  transfers,
  incomings,
  accounts,
  form,
  setForm,
  onSelect,
  onTransferDetails,
}: {
  onTransferDetails: (id: number) => void;
  transfers: PaginatedResult<TransferDetails[]>;
  incomings: PaginatedResult<ExpectedTransferEntry[]>;
  accounts: string[];
  setForm: StateUpdater<Form>;
  form: Form;
  onSelect: () => void;
}): VNode {
  const { i18n } = useTranslationContext();

  return (
    <Fragment>
      <section class="section is-main-section">
        <div class="columns">
          <div class="column" />
          <div class="column is-10">
            <FormProvider object={form} valueHandler={setForm}>
              <InputSelector
                name="payto_uri"
                label={i18n.str`Bank account`}
                values={accounts}
                fromStr={(d) => {
                  const idx = accounts.indexOf(d);
                  if (idx === -1) return undefined;
                  return d;
                }}
                placeholder={i18n.str`All accounts`}
                tooltip={i18n.str`Filter by account address`}
              />
              <InputToggle
                label={i18n.str`Verified`}
                tooltip={i18n.str`A wire transfer is verified if match the amount of all orders being settled.`}
                name="verified"
                threeState
              />
            </FormProvider>
          </div>
          <div class="column" />
        </div>
      </section>

      <ListPage
        transfers={transfers}
        incomings={incomings}
        onSelectedToConfirm={(e) =>
          onTransferDetails(e.expected_transfer_serial_id!)
        }
      />
    </Fragment>
  );
}
