import React, { ReactElement, useEffect } from 'react';
import Head from 'next/head';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import dayjs from 'dayjs';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { fetch } from '../../stores/devices/devicesSlice';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from '../../components/ImageField';
import LayoutAuthenticated from '../../layouts/Authenticated';
import { getPageTitle } from '../../config';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import SectionMain from '../../components/SectionMain';
import CardBox from '../../components/CardBox';
import BaseButton from '../../components/BaseButton';
import BaseDivider from '../../components/BaseDivider';
import { mdiChartTimelineVariant } from '@mdi/js';
import { SwitchField } from '../../components/SwitchField';
import FormField from '../../components/FormField';

import { hasPermission } from '../../helpers/userPermissions';

const DevicesView = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { devices } = useAppSelector((state) => state.devices);

  const { currentUser } = useAppSelector((state) => state.auth);

  const { id } = router.query;

  function removeLastCharacter(str) {
    console.log(str, `str`);
    return str.slice(0, -1);
  }

  useEffect(() => {
    dispatch(fetch({ id }));
  }, [dispatch, id]);

  return (
    <>
      <Head>
        <title>{getPageTitle('View devices')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={removeLastCharacter('View devices')}
          main
        >
          <BaseButton
            color='info'
            label='Edit'
            href={`/devices/devices-edit/?id=${id}`}
          />
        </SectionTitleLineWithButton>
        <CardBox>
          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Type</p>
            <p>{devices?.type ?? 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Platform</p>
            <p>{devices?.platform ?? 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Serial</p>
            <p>{devices?.serial}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>AssetTag</p>
            <p>{devices?.asset_tag}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Owner</p>

            <p>{devices?.owner?.user ?? 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Status</p>
            <p>{devices?.status ?? 'No data'}</p>
          </div>

          <FormField label='Encryption'>
            <SwitchField
              field={{ name: 'encryption', value: devices?.encryption }}
              form={{ setFieldValue: () => null }}
              disabled
            />
          </FormField>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>OSVersion</p>
            <p>{devices?.os_version}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>organizations</p>

            <p>{devices?.organizations?.name ?? 'No data'}</p>
          </div>

          <>
            <p className={'block font-bold mb-2'}>Inventory_events Device</p>
            <CardBox
              className='mb-6 border border-gray-300 rounded overflow-hidden'
              hasTable
            >
              <div className='overflow-x-auto'>
                <table>
                  <thead>
                    <tr>
                      <th>EventType</th>

                      <th>Timestamp</th>

                      <th>Metadata</th>
                    </tr>
                  </thead>
                  <tbody>
                    {devices.inventory_events_device &&
                      Array.isArray(devices.inventory_events_device) &&
                      devices.inventory_events_device.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/inventory_events/inventory_events-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='event_type'>{item.event_type}</td>

                          <td data-label='timestamp'>
                            {dataFormatter.dateTimeFormatter(item.timestamp)}
                          </td>

                          <td data-label='metadata'>{item.metadata}</td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
              {!devices?.inventory_events_device?.length && (
                <div className={'text-center py-4'}>No data</div>
              )}
            </CardBox>
          </>

          <BaseDivider />

          <BaseButton
            color='info'
            label='Back'
            onClick={() => router.push('/devices/devices-list')}
          />
        </CardBox>
      </SectionMain>
    </>
  );
};

DevicesView.getLayout = function getLayout(page: ReactElement) {
  return (
    <LayoutAuthenticated permission={'READ_DEVICES'}>
      {page}
    </LayoutAuthenticated>
  );
};

export default DevicesView;
