import {
  IonButton,
  IonButtons,
  IonCard,
  IonCardContent,
  IonCardHeader,
  IonCardTitle,
  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';
import i18n from '../../i18n/index';

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}
        className='full-height'
        trigger='track-browser-button'
        enterAnimation={enterAnimation}
        leaveAnimation={leaveAnimation}
      >
        <IonToolbar>
          <IonTitle>{i18n.tracks}</IonTitle>
          <IonButtons slot='end'>
            <GpxImport />
            <IonButton onClick={() => dismiss()}>{i18n.close}</IonButton>
          </IonButtons>
        </IonToolbar>
        <IonContent>
          {gpxes.map((gpx: any) => (
            <IonCard key={gpx._id}>
              <IonCardHeader>
                <IonItem>
                  <IonCardTitle>{gpx.gpx.metadata.name}</IonCardTitle>
                  <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>
                <IonCardContent>
                  <IonList>
                    <IonItem>{gpx.gpx.metadata.time}</IonItem>
                    <IonItem>{gpx.gpx.metadata.desc}</IonItem>
                  </IonList>
                </IonCardContent>
              </IonCardHeader>
            </IonCard>
          ))}
        </IonContent>
      </IonModal>
    </Fragment>
  );
};

export default TrackBrowser;
