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

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>ProjectCode</p>
            <p>{projects?.code}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>ProjectType</p>
            <p>{projects?.type ?? 'No data'}</p>
          </div>

          {hasPermission(currentUser, 'READ_ORGANIZATIONS') && (
            <div className={'mb-4'}>
              <p className={'block font-bold mb-2'}>Organization</p>

              <p>{projects?.organization?.name ?? 'No data'}</p>
            </div>
          )}

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

            <p>{projects?.organizations?.name ?? 'No data'}</p>
          </div>

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

                      <th>DocumentType</th>

                      <th>PreparedBy</th>

                      <th>Status</th>

                      <th>CashBalance</th>

                      <th>PaymentDate</th>

                      <th>Amount</th>

                      <th>ShelfNumber</th>

                      <th>ApprovedBy</th>
                    </tr>
                  </thead>
                  <tbody>
                    {projects.documents_project &&
                      Array.isArray(projects.documents_project) &&
                      projects.documents_project.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/documents/documents-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='document_number'>
                            {item.document_number}
                          </td>

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

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

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

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

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

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

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

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

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

                      <th>EmployeeName</th>

                      <th>DeparturePlace</th>

                      <th>DepartureDate</th>

                      <th>ArrivalPlace</th>

                      <th>ReturnDate</th>

                      <th>RequisitionDate</th>

                      <th>RequestedAmount</th>

                      <th>PaymentType</th>

                      <th>Status</th>

                      <th>Requester</th>

                      <th>Approver</th>

                      <th>DueDate</th>
                    </tr>
                  </thead>
                  <tbody>
                    {projects.field_site_payment_requisitions_project &&
                      Array.isArray(
                        projects.field_site_payment_requisitions_project,
                      ) &&
                      projects.field_site_payment_requisitions_project.map(
                        (item: any) => (
                          <tr
                            key={item.id}
                            onClick={() =>
                              router.push(
                                `/field_site_payment_requisitions/field_site_payment_requisitions-view/?id=${item.id}`,
                              )
                            }
                          >
                            <td data-label='department'>{item.department}</td>

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

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

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

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

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

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

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

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

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

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

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

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

          <BaseDivider />

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

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

export default ProjectsView;
