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'}>Schools</p>

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

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

                      <th>EntityID</th>

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

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

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

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

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

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

                      <th>IPAddress</th>

                      <th>DeviceInfo</th>
                    </tr>
                  </thead>
                  <tbody>
                    {users.login_logs_user &&
                      Array.isArray(users.login_logs_user) &&
                      users.login_logs_user.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/login_logs/login_logs-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='login_time'>
                            {dataFormatter.dateTimeFormatter(item.login_time)}
                          </td>

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

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

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

                      <th>MessageType</th>

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

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

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

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

                      <th>MessageType</th>

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

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

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

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

                      <th>PhoneNumber</th>

                      <th>Address</th>
                    </tr>
                  </thead>
                  <tbody>
                    {users.parents_user &&
                      Array.isArray(users.parents_user) &&
                      users.parents_user.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(`/parents/parents-view/?id=${item.id}`)
                          }
                        >
                          <td data-label='full_name'>{item.full_name}</td>

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

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

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

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

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

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

                      <th>DateofBirth</th>

                      <th>Gender</th>

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

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

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

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

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

                      <th>SubjectSpecialization</th>

                      <th>PhoneNumber</th>

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

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

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

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