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

/**
 *
 * @author Martin Schanzenbach
 */

import { AbsoluteTime } from "@gnu-taler/taler-util";
import { useTranslationContext } from "@gnu-taler/web-util/browser";
import { format } from "date-fns";
import { Fragment, VNode, h } from "preact";
import { useState } from "preact/hooks";
import { DatePicker } from "../../../../components/picker/DatePicker.js";
import { dateFormatForSettings, usePreference } from "../../../../hooks/preference.js";
import { Line } from "react-chartjs-2";
import { ChartDataset, Point } from "chart.js";

const TALER_SCREEN_ID = 58;

export interface OrdersChartProps {
  chartData: ChartDataset[];
  chartLabels: number[];
  chartOptions: any;
  filterFromDate?: AbsoluteTime;
  onSelectDate: (date?: AbsoluteTime) => void;
}

export function OrdersChart({
  chartData,
  chartLabels,
  chartOptions,
  filterFromDate,
  onSelectDate,
}: OrdersChartProps): VNode {
  const { i18n } = useTranslationContext();
  const [settings] = usePreference();
  const dateTooltip = i18n.str`Select date from which to show statistics`;
  const [pickDate, setPickDate] = useState(false);
  const [showTable, setShowTable] = useState<boolean>(false);
  function getCountForLabelAndDataset(label: number, ds: ChartDataset) : number {
    for (let d of (ds.data as Array<Point>)) {
      if (d.x === label) {
        return d.y;
      }
    }
    return 0;
  }
  return (
    <Fragment>
      <div class="tabs" style={{ overflow: "inherit" }}>
         <ul>
           <li class={(!showTable) ? "is-active" : ""}>
             <div
               class="has-tooltip-right"
               data-tooltip={i18n.str`Show chart`}
             >
               <a onClick={() => {setShowTable(false) }}>
                 <i18n.Translate>Orders chart</i18n.Translate>
               </a>
             </div>
             </li>
           <li class={(showTable) ? "is-active" : ""}>
             <div
               class="has-tooltip-right"
               data-tooltip={i18n.str`Show table`}
             >
               <a onClick={() => {setShowTable(true) }}>
                 <i18n.Translate>Orders table</i18n.Translate>
               </a>
             </div>
           </li>
         </ul>
       </div>
       <div class="columns">
       <div class="column">
          <div class="buttons is-right">
            <div class="field has-addons">
              {filterFromDate && (
                <div class="control">
                  <a class="button is-fullwidth" onClick={() => onSelectDate(undefined)}>
                    <span
                      class="icon"
                      data-tooltip={i18n.str`Clear date filter`}
                    >
                      <i class="mdi mdi-close" />
                    </span>
                  </a>
                </div>
              )}
              <div class="control">
                <span class="has-tooltip-top" data-tooltip={dateTooltip}>
                  <input
                    class="input"
                    type="text"
                    readonly
                    value={!filterFromDate || filterFromDate.t_ms === "never" ? "" : format(filterFromDate.t_ms, dateFormatForSettings(settings))}
                    placeholder={i18n.str`Start from (${dateFormatForSettings(settings)})`}
                    onClick={() => {
                      setPickDate(true);
                    }}
                  />
                </span>
              </div>
              <div class="control">
                <span class="has-tooltip-left" data-tooltip={dateTooltip}>
                  <a
                    class="button  is-fullwidth"
                    onClick={() => {
                      setPickDate(true);
                    }}
                  >
                    <span class="icon">
                      <i class="mdi mdi-calendar" />
                    </span>
                  </a>
                </span>
              </div>
            </div>
          </div>
        </div>
        </div>

      <DatePicker
        opened={pickDate}
        closeFunction={() => setPickDate(false)}
        dateReceiver={(d) => {
          onSelectDate(AbsoluteTime.fromMilliseconds(d.getTime()))
        }}
      />
     <div class="card has-table">
        <header class="card-header">
          <p class="card-header-title">
            <span class="icon">
              <i class="mdi mdi-shopping" />
            </span>
            {i18n.str`Orders statistics`}
          </p>
        </header>
        <div class="card-content">
          {(chartData && chartLabels.length > 0) ? (
            (!showTable) ? (
              <Line data={{labels: chartLabels, datasets: chartData as any}} options={chartOptions}/>
            ) : (
              <div class="b-table has-pagination">
                 <div class="table-wrapper has-mobile-cards">
                   <div class="table-container">
                     <table class="table is-fullwidth is-striped is-hoverable is-fullwidth">
                       <thead>
                         <tr>
                           <th>
                             <i18n.Translate>Since</i18n.Translate>
                           </th>
                          {chartData!.map((d) => {
                             return (
                               <Fragment key={d.label}>
                               <th>
                                   {d.label}
                                 </th>
                               </Fragment>
                             )})}
                         </tr>
                       </thead>
                       <tbody>
                          {chartLabels.map((l) => {
                             return (
                               <Fragment key={l}>
                                 <tr key="info">
                                   <td>
                                   {new Date(l).toLocaleString()}
                                   </td>
                                   {chartData?.map((d) => {
                                     return (
                                       <Fragment key={d.label}>
                                       <td>
                                       {getCountForLabelAndDataset(l, d)}
                                     </td>
                                       </Fragment>
                                   );})}
                                 </tr>
                               </Fragment>
                             );
                           })}
                       </tbody>
                     </table>
                   </div>
                 </div>
               </div>

            )
          ) : (
          <i>{i18n.str`No order statistics yet.`}</i>
          )
          }
        </div>
      </div>
    </Fragment>
  );
}
