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

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

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Period</p>
            <p>{plans?.period ?? 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>PriceMAD</p>
            <p>{plans?.price_mad || 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Limits</p>
            <p>{plans?.limits}</p>
          </div>

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

            <p>{plans?.agences?.name ?? 'No data'}</p>
          </div>

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

                      <th>CurrentPeriodStart</th>

                      <th>CurrentPeriodEnd</th>

                      <th>PaymentProvider</th>

                      <th>ProviderCustomerID</th>

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

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

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

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

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

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

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

                      <th>Subdomain</th>

                      <th>Status</th>

                      <th>TrialEndsAt</th>

                      <th>BillingEmail</th>

                      <th>BillingPhone</th>
                    </tr>
                  </thead>
                  <tbody>
                    {plans.tenants_plan &&
                      Array.isArray(plans.tenants_plan) &&
                      plans.tenants_plan.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(`/tenants/tenants-view/?id=${item.id}`)
                          }
                        >
                          <td data-label='name'>{item.name}</td>

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

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

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

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

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

          <BaseDivider />

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

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

export default PlansView;
