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/users/usersSlice';
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 type { User, Role } from '../../types/entities';

// Extended User type for view page with related entities
interface UserWithRelations extends User {
  project_memberships_user?: Array<{
    id: string;
    access_level?: string;
    is_active?: boolean;
    invited_at?: string;
    accepted_at?: string;
  }>;
  presigned_url_requests_user?: Array<{
    id: string;
    purpose?: string;
    asset_type?: string;
    requested_key?: string;
    mime_type?: string;
    requested_size_mb?: number;
    expires_at?: string;
    status?: string;
  }>;
  publish_events_user?: Array<{
    id: string;
    from_environment?: string;
    to_environment?: string;
    started_at?: string;
    finished_at?: string;
    status?: string;
    error_message?: string;
    pages_copied?: number;
    transitions_copied?: number;
    audios_copied?: number;
  }>;
  access_logs_user?: Array<{
    id: string;
    environment?: string;
    path?: string;
    ip_address?: string;
    user_agent?: string;
    accessed_at?: string;
  }>;
}

const UsersView = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const usersState = useAppSelector((state) => state.users);
  const users = usersState.users as
    | UserWithRelations
    | UserWithRelations[]
    | undefined;
  const user = Array.isArray(users) ? users[0] : users;

  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 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>{user?.firstName}</p>
          </div>

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

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

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

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Avatar</p>
            {user?.avatar?.length ? (
              <ImageField
                name={'avatar'}
                image={user?.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>
              {typeof user?.app_role === 'object' && user?.app_role !== null
                ? (user.app_role as 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>
                    {user?.custom_permissions &&
                      Array.isArray(user.custom_permissions) &&
                      user.custom_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>
              {!user?.custom_permissions?.length && (
                <div className={'text-center py-4'}>No data</div>
              )}
            </CardBox>
          </>

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

                      <th>Isactive</th>

                      <th>Invitedat</th>

                      <th>Acceptedat</th>
                    </tr>
                  </thead>
                  <tbody>
                    {user?.project_memberships_user &&
                      Array.isArray(user.project_memberships_user) &&
                      user.project_memberships_user.map(
                        (item: {
                          id: string;
                          access_level?: string;
                          is_active?: boolean;
                          invited_at?: string;
                          accepted_at?: string;
                        }) => (
                          <tr
                            key={item.id}
                            onClick={() =>
                              router.push(
                                `/project_memberships/project_memberships-view/?id=${item.id}`,
                              )
                            }
                          >
                            <td data-label='access_level'>
                              {item.access_level}
                            </td>

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

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

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

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

                      <th>Assettype</th>

                      <th>Requestedkey</th>

                      <th>MIMEtype</th>

                      <th>Requestedsize(MB)</th>

                      <th>Expiresat</th>

                      <th>Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {user?.presigned_url_requests_user &&
                      Array.isArray(user.presigned_url_requests_user) &&
                      user.presigned_url_requests_user.map(
                        (item: {
                          id: string;
                          purpose?: string;
                          asset_type?: string;
                          requested_key?: string;
                          mime_type?: string;
                          requested_size_mb?: number;
                          expires_at?: string;
                          status?: string;
                        }) => (
                          <tr
                            key={item.id}
                            onClick={() =>
                              router.push(
                                `/presigned_url_requests/presigned_url_requests-view/?id=${item.id}`,
                              )
                            }
                          >
                            <td data-label='purpose'>{item.purpose}</td>

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

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

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

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

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

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

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

                      <th>Toenvironment</th>

                      <th>Startedat</th>

                      <th>Finishedat</th>

                      <th>Status</th>

                      <th>Errormessage</th>

                      <th>Pagescopied</th>

                      <th>Transitionscopied</th>

                      <th>Audioscopied</th>
                    </tr>
                  </thead>
                  <tbody>
                    {user?.publish_events_user &&
                      Array.isArray(user.publish_events_user) &&
                      user.publish_events_user.map(
                        (item: {
                          id: string;
                          from_environment?: string;
                          to_environment?: string;
                          started_at?: string;
                          finished_at?: string;
                          status?: string;
                          error_message?: string;
                          pages_copied?: number;
                          transitions_copied?: number;
                          audios_copied?: number;
                        }) => (
                          <tr
                            key={item.id}
                            onClick={() =>
                              router.push(
                                `/publish_events/publish_events-view/?id=${item.id}`,
                              )
                            }
                          >
                            <td data-label='from_environment'>
                              {item.from_environment}
                            </td>

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

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

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

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

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

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

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

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

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

                      <th>Path</th>

                      <th>IPaddress</th>

                      <th>Useragent</th>

                      <th>Accessedat</th>
                    </tr>
                  </thead>
                  <tbody>
                    {user?.access_logs_user &&
                      Array.isArray(user.access_logs_user) &&
                      user.access_logs_user.map(
                        (item: {
                          id: string;
                          environment?: string;
                          path?: string;
                          ip_address?: string;
                          user_agent?: string;
                          accessed_at?: string;
                        }) => (
                          <tr
                            key={item.id}
                            onClick={() =>
                              router.push(
                                `/access_logs/access_logs-view/?id=${item.id}`,
                              )
                            }
                          >
                            <td data-label='environment'>{item.environment}</td>

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

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

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

                            <td data-label='accessed_at'>
                              {dataFormatter.dateTimeFormatter(
                                item.accessed_at,
                              )}
                            </td>
                          </tr>
                        ),
                      )}
                  </tbody>
                </table>
              </div>
              {!user?.access_logs_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;
