import React, { ReactElement, useEffect } from 'react';
import Head from 'next/head';
import 'react-datepicker/dist/react-datepicker.css';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { fetch } from '../../stores/roles/rolesSlice';
import dataFormatter from '../../helpers/dataFormatter';
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 type { Role } from '../../types/entities';

// Extended Role type for view page with related entities
interface RoleWithRelations extends Role {
  users_app_role?: Array<{
    id: string;
    firstName?: string;
    lastName?: string;
    phoneNumber?: string;
    email?: string;
    disabled?: boolean;
  }>;
}

const RolesView = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const rolesState = useAppSelector((state) => state.roles);
  const roles = rolesState.roles as
    | RoleWithRelations
    | RoleWithRelations[]
    | undefined;
  const role = Array.isArray(roles) ? roles[0] : roles;

  const { id } = router.query as { id?: string };

  function removeLastCharacter(str: string): string {
    return str.slice(0, -1);
  }

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

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

          <>
            <p className={'block font-bold mb-2'}>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>
                    {role?.permissions &&
                      Array.isArray(role.permissions) &&
                      role.permissions.map(
                        (item: { id: string; name?: string }) => (
                          <tr
                            key={item.id}
                            onClick={() =>
                              router.push(
                                `/permissions/permissions-view/?id=${item.id}`,
                              )
                            }
                          >
                            <td data-label='name'>{item.name}</td>
                          </tr>
                        ),
                      )}
                  </tbody>
                </table>
              </div>
              {!role?.permissions?.length && (
                <div className={'text-center py-4'}>No data</div>
              )}
            </CardBox>
          </>

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

                      <th>Last Name</th>

                      <th>Phone Number</th>

                      <th>E-Mail</th>

                      <th>Disabled</th>
                    </tr>
                  </thead>
                  <tbody>
                    {role?.users_app_role &&
                      Array.isArray(role.users_app_role) &&
                      role.users_app_role.map(
                        (item: {
                          id: string;
                          firstName?: string;
                          lastName?: string;
                          phoneNumber?: string;
                          email?: string;
                          disabled?: boolean;
                        }) => (
                          <tr
                            key={item.id}
                            onClick={() =>
                              router.push(`/users/users-view/?id=${item.id}`)
                            }
                          >
                            <td data-label='firstName'>{item.firstName}</td>

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

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

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

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

          <BaseDivider />

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

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

export default RolesView;
