import React, { useEffect, useState } from 'react';
import { FlightTable } from './flight-table';
import { Tabs } from '../tabs/tabs';

import {
  getFlights,
  Flight,
  Aircraft,
  getAircrafts,
  getUsers,
  User,
} from '../../airtable-data';

export const FlightTableDemo1 = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [flights, setFlights] = useState<Flight[]>([]);
  const [aircrafts, setAircrafts] = useState<Aircraft[]>([]);

  useEffect(() => {
    getUsers().then(({ records }) => {
      setUsers(records);
    });
    getFlights().then(({ records }) => {
      setFlights(records);
    });
    getAircrafts().then(({ records }) => {
      setAircrafts(records);
    });
  }, []);

  const isString = (string: string): string =>
    typeof string === 'string' ? string : '-';
  function checkTypes(input: any[] | string): string {
    if (Array.isArray(input)) {
      if (input.length > 0) {
        return isString(input[0]);
      }
      return '';
    }
    return isString(input);
  }

  const columns = [
    {
      Header: 'Date',
      accessor: 'date',
    },
    {
      Header: 'Type',
      accessor: 'type',
    },
    {
      Header: 'Aircraft',
      accessor: 'aircraft',
    },
    {
      Header: 'Route',
      accessor: 'route',
    },
    {
      Header: 'Dep - Arr',
      accessor: 'depArr',
    },
    {
      Header: 'Pilot',
      accessor: 'pilot',
    },
    {
      Header: 'Co-Pilot',
      accessor: 'coPilot',
    },
    {
      // Make an expander cell
      Header: 'Actions',
      id: 'actions', // It needs an ID
      Cell: ({ row }) => (
        // Use Cell to render an expander for each row.
        // We can use the getToggleRowExpandedProps prop-getter
        // to build the expander.
        <span {...row.getToggleRowExpandedProps()}>
          View{' '}
          {row.isExpanded ? (
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
              <path
                d="M32.548.876l.018.018a2.989,2.989,0,0,1,0,4.233L7.636,30l24.93,24.873a2.988,2.988,0,0,1,0,4.232l-.018.019a3.006,3.006,0,0,1-4.243,0L.782,31.664a2.151,2.151,0,0,1-.129-3.2L28.305.876a3.006,3.006,0,0,1,4.243,0Z"
                transform="translate(2 49.444) rotate(-90)"
              />
            </svg>
          ) : (
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
              <path
                d="M4957.9,3422.124l-.018-.018a2.989,2.989,0,0,1,0-4.233L4982.81,3393l-24.93-24.873a2.988,2.988,0,0,1,0-4.232l.018-.019a3.006,3.006,0,0,1,4.243,0l27.523,27.46a2.151,2.151,0,0,1,.129,3.2l-27.653,27.588a3.006,3.006,0,0,1-4.243,0Z"
                transform="translate(-4941.001 -3360.875)"
              />
            </svg>
          )}
        </span>
      ),
    },
  ];

  // Create a function that will render our row sub components
  const renderRowSubComponent = React.useCallback(
    ({ row }) => (
      <pre
        style={{
          fontSize: '10px',
        }}
      >
        <code>{JSON.stringify({ values: row.values }, null, 2)}</code>
      </pre>
    ),
    [],
  );

  if (!flights && !aircrafts) return null;
  const data = flights.map(flight => {
    const dataSet = {
      date: checkTypes(flight.fields['Flight-date-short']),
      type: checkTypes(flight.fields['Mission Type']),
      aircraft: '-',
      route: checkTypes(flight.fields['Route-short']),
      depArr: '',
      pilot: '-',
      coPilot: '-',
      departureDate: flight.fields['Scheduled Departure'],
    };

    // Check aircraft data and return aircraft name based on ID given in flight info
    const aircraftId = checkTypes(flight.fields.Aircraft);
    const aircraft = aircrafts.find(a => a.id === aircraftId);

    if (aircraft && typeof aircraft.fields['N-Number'] === 'number') {
      dataSet.aircraft = `N${aircraft.fields['N-Number']}`;
    }

    const pilotId = checkTypes(flight.fields.Pilot);
    const pilot = users.find(p => p.id === pilotId);

    // Check Pilot data and return full name based on ID given in flight info
    if (
      pilot &&
      typeof pilot.fields['First Name'] === 'string' &&
      typeof pilot.fields['Last Name'] === 'string'
    ) {
      dataSet.pilot = `${pilot.fields['First Name']} ${pilot.fields['Last Name']}`;
    }

    const coPilotId = checkTypes(flight.fields['Co-Pilot']);
    const coPilot = users.find(p => p.id === coPilotId);

    // Check Co-Pilot data and return full name based on ID given in flight info
    if (
      coPilot &&
      typeof coPilot.fields['First Name'] === 'string' &&
      typeof coPilot.fields['Last Name'] === 'string'
    ) {
      dataSet.coPilot = `${coPilot.fields['First Name']} ${coPilot.fields['Last Name']}`;
    }

    // Check departure and arival data and return combined Dep - Arr field
    const dep = checkTypes(flight.fields['Departure-short']);
    const arrival = checkTypes(flight.fields['Arrival-Short']);
    if (dep !== '-' && arrival !== '-') {
      dataSet.depArr = `${dep} - ${arrival}`;
    } else {
      dataSet.depArr = '-';
    }
    return dataSet;
  });

  const date = new Date();

  const pastFlights = data.filter(
    flight => new Date(flight.departureDate) <= date,
  );
  const futureFlights = data.filter(
    flight => new Date(flight.departureDate) > date,
  );

  return (
    <Tabs
      items={[
        {
          id: '1',
          title: 'Scheduled',
          children: (
            <FlightTable
              columns={columns}
              data={futureFlights}
              // We added this as a prop for our table component
              // This is not part of the React Table API,
              // it's merely a rendering option we created for
              // ourselves
              renderRowSubComponent={renderRowSubComponent}
            />
          ),
        },
        {
          id: '2',
          title: 'History',
          children: (
            <FlightTable
              columns={columns}
              data={pastFlights}
              // We added this as a prop for our table component
              // This is not part of the React Table API,
              // it's merely a rendering option we created for
              // ourselves
              renderRowSubComponent={renderRowSubComponent}
            />
          ),
        },
      ]}
    />
  );
};
