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

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>TCNumber</p>
            <p>{partners?.tc_number}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>TaxNumber</p>
            <p>{partners?.tax_number}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>InsuranceNumber</p>
            <p>{partners?.insurance_number}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Phone</p>
            <p>{partners?.phone}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Sector</p>
            <p>{partners?.sector}</p>
          </div>

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

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

            <p>{partners?.kooperatif?.name ?? 'No data'}</p>
          </div>

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

                      <th>DebtLimit</th>

                      <th>CurrentDebt</th>

                      <th>AccountType</th>
                    </tr>
                  </thead>
                  <tbody>
                    {partners.accounts_partner &&
                      Array.isArray(partners.accounts_partner) &&
                      partners.accounts_partner.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/accounts/accounts-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='balance'>{item.balance}</td>

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

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

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

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

                      <th>OfferDate</th>
                    </tr>
                  </thead>
                  <tbody>
                    {partners.barter_offers_partner &&
                      Array.isArray(partners.barter_offers_partner) &&
                      partners.barter_offers_partner.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/barter_offers/barter_offers-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='offer_details'>
                            {item.offer_details}
                          </td>

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

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

                      <th>DueDate</th>

                      <th>Notified</th>
                    </tr>
                  </thead>
                  <tbody>
                    {partners.delayed_payments_partner &&
                      Array.isArray(partners.delayed_payments_partner) &&
                      partners.delayed_payments_partner.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/delayed_payments/delayed_payments-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='amount'>{item.amount}</td>

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

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

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

                      <th>LoanType</th>

                      <th>ApplicationDate</th>

                      <th>Approved</th>
                    </tr>
                  </thead>
                  <tbody>
                    {partners.loan_applications_partner &&
                      Array.isArray(partners.loan_applications_partner) &&
                      partners.loan_applications_partner.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/loan_applications/loan_applications-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='amount'>{item.amount}</td>

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

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

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

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

                      <th>StartDate</th>

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

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

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

          <BaseDivider />

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

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

export default PartnersView;
