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/subscribers/subscribersSlice';
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 SubscribersView = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { subscribers } = useAppSelector((state) => state.subscribers);

  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 subscribers')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={removeLastCharacter('View subscribers')}
          main
        >
          <BaseButton
            color='info'
            label='Edit'
            href={`/subscribers/subscribers-edit/?id=${id}`}
          />
        </SectionTitleLineWithButton>
        <CardBox>
          {hasPermission(currentUser, 'READ_ORGANIZATIONS') && (
            <div className={'mb-4'}>
              <p className={'block font-bold mb-2'}>Organization</p>

              <p>{subscribers?.organization?.name ?? 'No data'}</p>
            </div>
          )}

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Name</p>
            <p>{subscribers?.name}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Organization</p>
            <p>{subscribers?.org}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Email</p>
            <p>{subscribers?.email}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Role</p>
            <p>{subscribers?.role ?? 'No data'}</p>
          </div>

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

          <FormField label='LastLogin'>
            {subscribers.last_login ? (
              <DatePicker
                dateFormat='yyyy-MM-dd hh:mm'
                showTimeSelect
                selected={
                  subscribers.last_login
                    ? new Date(
                        dayjs(subscribers.last_login).format(
                          'YYYY-MM-DD hh:mm',
                        ),
                      )
                    : null
                }
                disabled
              />
            ) : (
              <p>No LastLogin</p>
            )}
          </FormField>

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

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

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

                      <th>Prescriptions</th>

                      <th>Appointments</th>

                      <th>Billing</th>
                    </tr>
                  </thead>
                  <tbody>
                    {subscribers.patient_profiles_subscriber &&
                      Array.isArray(subscribers.patient_profiles_subscriber) &&
                      subscribers.patient_profiles_subscriber.map(
                        (item: any) => (
                          <tr
                            key={item.id}
                            onClick={() =>
                              router.push(
                                `/patient_profiles/patient_profiles-view/?id=${item.id}`,
                              )
                            }
                          >
                            <td data-label='health_metrics'>
                              {item.health_metrics}
                            </td>

                            <td data-label='prescriptions'>
                              {item.prescriptions}
                            </td>

                            <td data-label='appointments'>
                              {item.appointments}
                            </td>

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

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

                      <th>Object</th>

                      <th>Timestamp</th>
                    </tr>
                  </thead>
                  <tbody>
                    {subscribers.subscriber_activities_subscriber &&
                      Array.isArray(
                        subscribers.subscriber_activities_subscriber,
                      ) &&
                      subscribers.subscriber_activities_subscriber.map(
                        (item: any) => (
                          <tr
                            key={item.id}
                            onClick={() =>
                              router.push(
                                `/subscriber_activities/subscriber_activities-view/?id=${item.id}`,
                              )
                            }
                          >
                            <td data-label='action'>{item.action}</td>

                            <td data-label='object'>{item.object}</td>

                            <td data-label='timestamp'>
                              {dataFormatter.dateTimeFormatter(item.timestamp)}
                            </td>
                          </tr>
                        ),
                      )}
                  </tbody>
                </table>
              </div>
              {!subscribers?.subscriber_activities_subscriber?.length && (
                <div className={'text-center py-4'}>No data</div>
              )}
            </CardBox>
          </>

          <>
            <p className={'block font-bold mb-2'}>
              Subscriber_roles Subscriber
            </p>
            <CardBox
              className='mb-6 border border-gray-300 rounded overflow-hidden'
              hasTable
            >
              <div className='overflow-x-auto'>
                <table>
                  <thead>
                    <tr>
                      <th>RoleName</th>
                    </tr>
                  </thead>
                  <tbody>
                    {subscribers.subscriber_roles_subscriber &&
                      Array.isArray(subscribers.subscriber_roles_subscriber) &&
                      subscribers.subscriber_roles_subscriber.map(
                        (item: any) => (
                          <tr
                            key={item.id}
                            onClick={() =>
                              router.push(
                                `/subscriber_roles/subscriber_roles-view/?id=${item.id}`,
                              )
                            }
                          >
                            <td data-label='role_name'>{item.role_name}</td>
                          </tr>
                        ),
                      )}
                  </tbody>
                </table>
              </div>
              {!subscribers?.subscriber_roles_subscriber?.length && (
                <div className={'text-center py-4'}>No data</div>
              )}
            </CardBox>
          </>

          <BaseDivider />

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

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

export default SubscribersView;
