import {
  IonButton,
  IonButtons,
  IonContent,
  IonIcon,
  IonItem,
  IonList,
  IonModal,
  IonTitle,
  IonToolbar,
} from '@ionic/react';
import { trash } from 'ionicons/icons';
import React, { Fragment, useRef } from 'react';
import { useFind, useDB } from 'react-pouchdb';
import { deleteGps } from '../../db/gpx';
import { enterAnimation, leaveAnimation } from '../../lib/animation';
import phoneRoute from '../../theme/icons/font-gis/svg/routing/uEB08-phone-route-nons.svg';
import GpxImport from './gpx-import';
import GpxExport from './GpxExport';

const TrackBrowser: React.FC<{}> = () => {
  const gpxes = useFind({
    selector: {
      type: 'gpx',
    },
  });

  const db = useDB();

  const modal = useRef<HTMLIonModalElement>(null);

  const dismiss = () => {
    modal.current?.dismiss();
  };

  return (
    <Fragment>
      <IonButton id='track-browser-button'>
        <img src={phoneRoute} alt='GPS tracks' width='24px' />
      </IonButton>
      <IonModal
        ref={modal}
        trigger='track-browser-button'
        enterAnimation={enterAnimation}
        leaveAnimation={leaveAnimation}
      >
        <IonToolbar>
          <IonTitle>Tracks</IonTitle>
          <IonButtons slot='end'>
            <GpxImport />
            <IonButton onClick={() => dismiss()}>Close</IonButton>
          </IonButtons>
        </IonToolbar>
        <IonContent>
          <IonList>
            {gpxes.map((gpx: any) => {
              return (
                <IonItem key={gpx._id}>
                  <span>{gpx.gpx.metadata.time}</span>
                  <IonButtons slot='end'>
                    <GpxExport gpx={gpx} />
                    <IonButton
                      onClick={() => {
                        deleteGps(db, { _id: gpx._id, _rev: gpx._rev });
                      }}
                      color='danger'
                    >
                      <IonIcon slot='icon-only' icon={trash} />
                    </IonButton>
                  </IonButtons>
                </IonItem>
              );
            })}
          </IonList>
        </IonContent>
      </IonModal>
    </Fragment>
  );
};

export default TrackBrowser;
