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

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

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Phone Number</p>
            <p>{users?.phoneNumber}</p>
          </div>

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

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Avatar</p>
            {users?.avatar?.length ? (
              <ImageField
                name={'avatar'}
                image={users?.avatar}
                className='w-20 h-20'
              />
            ) : (
              <p>No Avatar</p>
            )}
          </div>

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

            <p>{users?.app_role?.name ?? 'No data'}</p>
          </div>

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

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

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

          <>
            <p className={'block font-bold mb-2'}>Audit_logs ActorUser</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>TargetType</th>

                      <th>TargetID</th>

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

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

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

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

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

                      <th>Status</th>

                      <th>VerificationToken</th>

                      <th>SSLStatus</th>
                    </tr>
                  </thead>
                  <tbody>
                    {users.domain_mappings_user &&
                      Array.isArray(users.domain_mappings_user) &&
                      users.domain_mappings_user.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/domain_mappings/domain_mappings-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='domain'>{item.domain}</td>

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

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

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

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

                      <th>ToEmail</th>

                      <th>ProviderID</th>

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

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

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

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

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

                      <th>Type</th>

                      <th>Width</th>

                      <th>Height</th>

                      <th>SizeBytes</th>
                    </tr>
                  </thead>
                  <tbody>
                    {users.media_assets_user &&
                      Array.isArray(users.media_assets_user) &&
                      users.media_assets_user.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/media_assets/media_assets-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='url'>{item.url}</td>

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

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

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

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

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

                      <th>Title</th>

                      <th>Bio</th>

                      <th>Status</th>

                      <th>PublishedAt</th>

                      <th>OGTitle</th>

                      <th>OGDescription</th>

                      <th>OGImageURL</th>
                    </tr>
                  </thead>
                  <tbody>
                    {users.profile_pages_user &&
                      Array.isArray(users.profile_pages_user) &&
                      users.profile_pages_user.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/profile_pages/profile_pages-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='slug'>{item.slug}</td>

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

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

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

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

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

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

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

          <>
            <p className={'block font-bold mb-2'}>Subscriptions User</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>TrialEndsAt</th>

                      <th>CurrentPeriodStart</th>

                      <th>CurrentPeriodEnd</th>

                      <th>CancelAtPeriodEnd</th>

                      <th>PSPCustomerID</th>
                    </tr>
                  </thead>
                  <tbody>
                    {users.subscriptions_user &&
                      Array.isArray(users.subscriptions_user) &&
                      users.subscriptions_user.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='trial_ends_at'>
                            {dataFormatter.dateTimeFormatter(
                              item.trial_ends_at,
                            )}
                          </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='cancel_at_period_end'>
                            {dataFormatter.booleanFormatter(
                              item.cancel_at_period_end,
                            )}
                          </td>

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

          <BaseDivider />

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

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

export default UsersView;
