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

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

            <p>{students?.user?.firstName ?? 'No data'}</p>
          </div>

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

            <p>{students?.school?.name ?? 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>FullName</p>
            <p>{students?.full_name}</p>
          </div>

          <FormField label='DateofBirth'>
            {students.dob ? (
              <DatePicker
                dateFormat='yyyy-MM-dd hh:mm'
                showTimeSelect
                selected={
                  students.dob
                    ? new Date(dayjs(students.dob).format('YYYY-MM-DD hh:mm'))
                    : null
                }
                disabled
              />
            ) : (
              <p>No DateofBirth</p>
            )}
          </FormField>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Gender</p>
            <p>{students?.gender ?? 'No data'}</p>
          </div>

          <FormField label='AdmissionDate'>
            {students.admission_date ? (
              <DatePicker
                dateFormat='yyyy-MM-dd hh:mm'
                showTimeSelect
                selected={
                  students.admission_date
                    ? new Date(
                        dayjs(students.admission_date).format(
                          'YYYY-MM-DD hh:mm',
                        ),
                      )
                    : null
                }
                disabled
              />
            ) : (
              <p>No AdmissionDate</p>
            )}
          </FormField>

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

            <p>{students?.parent?.full_name ?? 'No data'}</p>
          </div>

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

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

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

                      <th>Content</th>

                      <th>Grade</th>

                      <th>Feedback</th>
                    </tr>
                  </thead>
                  <tbody>
                    {students.assignment_submissions_student &&
                      Array.isArray(students.assignment_submissions_student) &&
                      students.assignment_submissions_student.map(
                        (item: any) => (
                          <tr
                            key={item.id}
                            onClick={() =>
                              router.push(
                                `/assignment_submissions/assignment_submissions-view/?id=${item.id}`,
                              )
                            }
                          >
                            <td data-label='submission_date'>
                              {dataFormatter.dateTimeFormatter(
                                item.submission_date,
                              )}
                            </td>

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

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

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

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

                      <th>PaymentDate</th>

                      <th>ReceiptURL</th>

                      <th>Term</th>

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

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

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

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

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

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

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

                      <th>Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {students.student_attendance_student &&
                      Array.isArray(students.student_attendance_student) &&
                      students.student_attendance_student.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/student_attendance/student_attendance-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='date'>
                            {dataFormatter.dateTimeFormatter(item.date)}
                          </td>

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

          <BaseDivider />

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

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

export default StudentsView;
