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

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

            <p>{subscriptions?.user?.firstName ?? 'No data'}</p>
          </div>

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

            <p>{subscriptions?.plan?.name ?? 'No data'}</p>
          </div>

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

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

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

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

          <FormField label='CancelAtPeriodEnd'>
            <SwitchField
              field={{
                name: 'cancel_at_period_end',
                value: subscriptions?.cancel_at_period_end,
              }}
              form={{ setFieldValue: () => null }}
              disabled
            />
          </FormField>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>PSPCustomerID</p>
            <p>{subscriptions?.psp_customer_id}</p>
          </div>

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

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

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

                      <th>Currency</th>

                      <th>PSPProvider</th>

                      <th>PSPTransactionID</th>

                      <th>Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {subscriptions.payment_transactions_subscription &&
                      Array.isArray(
                        subscriptions.payment_transactions_subscription,
                      ) &&
                      subscriptions.payment_transactions_subscription.map(
                        (item: any) => (
                          <tr
                            key={item.id}
                            onClick={() =>
                              router.push(
                                `/payment_transactions/payment_transactions-view/?id=${item.id}`,
                              )
                            }
                          >
                            <td data-label='amount_cents'>
                              {item.amount_cents}
                            </td>

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

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

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

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

          <BaseDivider />

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

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

export default SubscriptionsView;
