/*
 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 {
  QrCodeSpec
} from "@gnu-taler/taler-util";
import { useTranslationContext } from "@gnu-taler/web-util/browser";
import { styled } from "@linaria/react";
import { Fragment, h, VNode } from "preact";
import { ButtonHandler } from "../mui/handlers.js";
import { Modal } from "./Modal.js";
import { QR } from "./QR.js";
import { useState } from "preact/hooks";

const QRsTable = styled.table`
  width: 100%;
  & > tr > td {
    padding: 5px;
  }
  & > tr > td {
    border-spacing: 0px;
    border-radius: 4px;
    border: 1px black solid;
  }
  & > tr > td:nth-child(2n) {
    text-align: right;
    overflow-wrap: anywhere;
  }
`;

const AccordionCss = styled.div`
& > .accordion {
  color: #444;
  cursor: pointer;
  padding: 8px;
  font-size: large;
  width: 100%;
  text-align: left;
  border: none;
  outline: none;
  transition: 0.4s;
}

& > .panel {
  padding: 0 18px;
  background-color: white;
  display: none;
  overflow: hidden;
}`

interface Props { qrs: QrCodeSpec[], onClose: ButtonHandler };

function Accordion({ section, content, openedByDefault }: { section: string, content: string, openedByDefault?:boolean }): VNode {
  const [opened, setOpened] = useState(!!openedByDefault)
  return <AccordionCss>
    <button class={opened ? "accordion active" : "accordion"} onClick={() => { setOpened(!opened) }}>{section}</button>
    <div class="panel" style={{ display: opened ? "block" : "none" }}>
      <QR text={content} />
    </div>
  </AccordionCss>
}

export function ShowQRsForPaytoPopup({ qrs, onClose }: Props): VNode {
  const { i18n } = useTranslationContext();

  return (
    <Modal title="Qrs" onClose={onClose}>
      <div style={{ overflowY: "auto", height: "95%", padding: 5 }}>
        <QRsTable>
          {qrs.map((q, idx) => {

            return <tr key={idx}>
              <td>
                <Accordion section={q.type} content={q.qrContent} openedByDefault />
              </td>
            </tr>
          })}
        </QRsTable>
      </div>
    </Modal>
  );
}
