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

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

            <p>{assignments?.teacher?.full_name ?? 'No data'}</p>
          </div>

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

            <p>{assignments?.subject?.name ?? 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Title</p>
            <p>{assignments?.title}</p>
          </div>

          <FormField label='Multi Text' hasTextareaHeight>
            <textarea
              className={'w-full'}
              disabled
              value={assignments?.description}
            />
          </FormField>

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>AttachmentURL</p>
            <p>{assignments?.attachment_url}</p>
          </div>

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

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

          <>
            <p className={'block font-bold mb-2'}>
              Assignment_submissions Assignment
            </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>
                    {assignments.assignment_submissions_assignment &&
                      Array.isArray(
                        assignments.assignment_submissions_assignment,
                      ) &&
                      assignments.assignment_submissions_assignment.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>
              {!assignments?.assignment_submissions_assignment?.length && (
                <div className={'text-center py-4'}>No data</div>
              )}
            </CardBox>
          </>

          <BaseDivider />

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

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

export default AssignmentsView;
