/*
 This file is part of GNU Taler
 (C) 2025 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 {
  ContactEntry,
  ScopeInfo
} from "@gnu-taler/taler-util";
import { useState } from "preact/hooks";
import { useAlertContext } from "../context/alert.js";
import { ButtonHandler } from "../mui/handlers.js";

type State = State.Ready | State.NoContactFound | State.Selecting;

export namespace State {
  export interface NoContactFound {
    status: "no-contact-found";
    error: undefined;
  }
  export interface Ready {
    status: "ready";
    doSelect: ButtonHandler;
    selected: ContactEntry;
  }
  export interface Selecting {
    status: "selecting-contact";
    error: undefined;
    onSelection: (alias: string) => Promise<void>;
    onCancel: () => Promise<void>;
    list: ContactEntry[];
    initialValue: string;
  }
}

interface Props {
  scope: ScopeInfo;
  //list of contacts
  list: ContactEntry[];
}

export function useSelectedContact({
  list,
}: Props): State {
  const [isSelecting, setIsSelecting] = useState(false);
  const [selectedContact, setSelectedContact] = useState<string | undefined>(
    undefined,
  );
  const { pushAlertOnError } = useAlertContext();

  if (!list.length) {
    return {
      status: "no-contact-found",
      error: undefined,
    };
  }

  if (isSelecting) {
    const currentContact =
      selectedContact ??
      list[0].alias;
    return {
      status: "selecting-contact",
      error: undefined,
      list: list,
      initialValue: currentContact,
      onSelection: async (alias: string) => {
        setIsSelecting(false);
        setSelectedContact(alias);
      },
      onCancel: async () => {
        setIsSelecting(false);
      },
    };
  }

  {
    const found = !selectedContact
      ? undefined
      : list.find((e) => e.alias === selectedContact);
    if (found)
      return {
        status: "ready",
        doSelect: {
          onClick: pushAlertOnError(async () => setIsSelecting(true)),
        },
        selected: found,
      };
  }
  {
    const found = false
    if (found)
      return {
        status: "ready",
        doSelect: {
          onClick: pushAlertOnError(async () => setIsSelecting(true)),
        },
        selected: found,
      };
  }

  return {
    status: "ready",
    doSelect: {
      onClick: pushAlertOnError(async () => setIsSelecting(true)),
    },
    selected: list[0],
  };
}
