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

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

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

            <p>{documents?.project?.name ?? 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>DocumentType</p>
            <p>{documents?.document_type ?? 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>PreparedBy</p>
            <p>{documents?.prepared_by}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Status</p>
            <p>{documents?.status ?? 'No data'}</p>
          </div>

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

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Amount</p>
            <p>{documents?.amount || 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>ShelfNumber</p>
            <p>{documents?.shelf_number}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>ApprovedBy</p>
            <p>{documents?.approved_by}</p>
          </div>

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

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

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

                      <th>Amount</th>

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

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

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

          <BaseDivider />

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

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

export default DocumentsView;
