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

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

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

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

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

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

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

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

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

                      <th>Amount</th>
                    </tr>
                  </thead>
                  <tbody>
                    {payroll_runs.deductions_payroll_run &&
                      Array.isArray(payroll_runs.deductions_payroll_run) &&
                      payroll_runs.deductions_payroll_run.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/deductions/deductions-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='type'>{item.type}</td>

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

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

                      <th>Units</th>

                      <th>Rate</th>

                      <th>Amount</th>

                      <th>Currency</th>

                      <th>Taxable</th>
                    </tr>
                  </thead>
                  <tbody>
                    {payroll_runs.earnings_payroll_run &&
                      Array.isArray(payroll_runs.earnings_payroll_run) &&
                      payroll_runs.earnings_payroll_run.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/earnings/earnings-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='component'>{item.component}</td>

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

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

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

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

                          <td data-label='taxable'>
                            {dataFormatter.booleanFormatter(item.taxable)}
                          </td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
              {!payroll_runs?.earnings_payroll_run?.length && (
                <div className={'text-center py-4'}>No data</div>
              )}
            </CardBox>
          </>

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

                      <th>Amount</th>
                    </tr>
                  </thead>
                  <tbody>
                    {payroll_runs.taxes_payroll_run &&
                      Array.isArray(payroll_runs.taxes_payroll_run) &&
                      payroll_runs.taxes_payroll_run.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(`/taxes/taxes-view/?id=${item.id}`)
                          }
                        >
                          <td data-label='jurisdiction'>{item.jurisdiction}</td>

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

          <BaseDivider />

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

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

export default Payroll_runsView;
