import React, { useContext, useState } from 'react';
import { Button } from 'primereact/button';
import { Card } from 'primereact/card';
import { DataTable } from 'primereact/datatable';
import { Password } from 'primereact/password';
import { AuthContext } from '../contexts';
import { Auth, Session } from '../services';
import { BackendReturnStatus } from '../types';
import { Column } from 'primereact/column';

export const Overview: React.FC = () => {
  const [statusMessage, setStatusMessage] = useState<{ error: boolean; message: string }>({
    error: false,
    message: '',
  });
  const { auth, reloadAuth } = useContext(AuthContext);

  const regenerateKey = async () => {
    Auth.refreshRadarScopeKey().then((status) => {
      if (status === BackendReturnStatus.Unauthorized) {
        Session.setLastShownComponent('/overview');
        Auth.triggerLoginFlow();
      } else if (status === BackendReturnStatus.Failure) {
        setStatusMessage({
          error: true,
          message: 'Unable to regenerate the key',
        });
      } else {
        reloadAuth();
        setStatusMessage({
          error: false,
          message: 'Updated the key',
        });
      }
    });
  }

  const userInformation: any[] = [
    { vatsimId: auth.user.vatsimId, fullName: auth.user.fullName !== '' ? auth.user.fullName : 'Unknown' },
  ];

  const userData = (
    <>
      <div>
        <DataTable value={userInformation} showGridlines>
          <Column field='vatsimId' header='VATSIM ID'></Column>
          <Column field='fullName' header='Name'></Column>
        </DataTable>
      </div>
      <div>
        <h4>RADAR scope key</h4>
        <Password
          value={auth.user.radarScopeKey}
          className='mr-3'
          feedback={false}
          toggleMask
        />
        <Button
          label='Regenerate'
          className='p-button-outlined p-button-secondary'
          onClick={regenerateKey}
        />
        <div className={statusMessage.error ? 'text-red-500' : 'text-secondary'}>
          {statusMessage.message}
        </div>
      </div>
    </>
  );

  const initialSteps = (
    <ul>
      <li>Download current Euroscope plugin version</li>
      <li>Add plugin to your Euroscope installation</li>
      <li>Copy 'RADAR Scope key'</li>
      <li>Paste the key into the amankey.txt file next to AMAN.dll of the Euroscope installation</li>
      <li>Restart Euroscope</li>
      <li>Activate AMAN plugin in Euroscpe</li>
    </ul>
  )

  return (
    <>
      <div className='card flex align-items-top justify-content-start p-3'>
        <Card
          title='Controller data'
          className='text-left surface-100 w-18.5rem h-21rem flex mr-3'
          footer={userData}
        />
        <Card
          title='Installation steps for Euroscope'
          className='text-left surface-100 w-42.5rem h-17rem flex mr-3'
          footer={initialSteps}
        />
      </div>
    </>
  );
};
