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/loans/loansSlice'
import dataFormatter from '../../helpers/dataFormatter';
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";

const LoansView = () => {
    const router = useRouter()
    const dispatch = useAppDispatch()
    const { loans } = useAppSelector((state) => state.loans)

    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 loans')}</title>
          </Head>
          <SectionMain>
            <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={removeLastCharacter('View loans')} main>
                <BaseButton
                  color='info'
                  label='Edit'
                  href={`/loans/loans-edit/?id=${id}`}
                />
            </SectionTitleLineWithButton>
            <CardBox>

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

                <div className={'mb-4'}>
                  <p className={'block font-bold mb-2'}>PrincipalAmount</p>
                  <p>{loans?.principal_amount || 'No data'}</p>
                </div>

                <div className={'mb-4'}>
                  <p className={'block font-bold mb-2'}>Term</p>
                  <p>{loans?.term || 'No data'}</p>
                </div>

                <div className={'mb-4'}>
                  <p className={'block font-bold mb-2'}>PendingAmount</p>
                  <p>{loans?.pending_amount || 'No data'}</p>
                </div>

                <div className={'mb-4'}>
                  <p className={'block font-bold mb-2'}>LastPendingAmount</p>
                  <p>{loans?.last_pending_amount || 'No data'}</p>
                </div>

                <div className={'mb-4'}>
                  <p className={'block font-bold mb-2'}>Rate</p>
                  <p>{loans?.rate || 'No data'}</p>
                </div>

                <div className={'mb-4'}>
                  <p className={'block font-bold mb-2'}>CommissionRate</p>
                  <p>{loans?.commission_rate || 'No data'}</p>
                </div>

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

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

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

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

                <div className={'mb-4'}>
                  <p className={'block font-bold mb-2'}>FinishDiscount</p>
                  <p>{loans?.finish_discount || 'No data'}</p>
                </div>

                <div className={'mb-4'}>
                  <p className={'block font-bold mb-2'}>FinishDiscountAmount</p>
                  <p>{loans?.finish_discount_amount || 'No data'}</p>
                </div>

                <div className={'mb-4'}>
                  <p className={'block font-bold mb-2'}>AdminRate</p>
                  <p>{loans?.admin_rate || 'No data'}</p>
                </div>

                <div className={'mb-4'}>
                  <p className={'block font-bold mb-2'}>AdminAmount</p>
                  <p>{loans?.admin_amount || 'No data'}</p>
                </div>

                <div className={'mb-4'}>
                    <p className={'block font-bold mb-2'}>Purpose</p>
                    <p>{loans?.purpose}</p>
                </div>

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

                        <p>{loans?.status?.name ?? 'No data'}</p>

                </div>

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

                        <p>{loans?.client?.name_en ?? 'No data'}</p>

                </div>

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

                        <p>{loans?.staff?.name_en ?? 'No data'}</p>

                </div>

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

                        <p>{loans?.interest_rate?.name ?? 'No data'}</p>

                </div>

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

                        <p>{loans?.branch?.name ?? 'No data'}</p>

                </div>

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

                        <p>{loans?.loan_type?.name_en ?? 'No data'}</p>

                </div>

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

                                <th>StartPaymentDate</th>

                                <th>PaymentDate</th>

                                <th>LastPaymentPaidDate</th>

                                <th>Sort</th>

                                <th>DeductAmount</th>

                                <th>DeductPaidAmount</th>

                                <th>Interval</th>

                                <th>InterestAmount</th>

                                <th>CommissionAmount</th>

                                <th>TotalAmount</th>

                                <th>TotalPaidAmount</th>

                                <th>PenaltyAmount</th>

                                <th>PendingAmount</th>

                                <th>CrossAmount</th>

                                <th>Remark</th>

                            </tr>
                            </thead>
                            <tbody>
                            {loans.payments_loan && Array.isArray(loans.payments_loan) &&
                              loans.payments_loan.map((item: any) => (
                                <tr key={item.id} onClick={() => router.push(`/payments/payments-view/?id=${item.id}`)}>

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

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

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

                                    <td data-label="sort">
                                        { item.sort }
                                    </td>

                                    <td data-label="deduct_amount">
                                        { item.deduct_amount }
                                    </td>

                                    <td data-label="deduct_paid_amount">
                                        { item.deduct_paid_amount }
                                    </td>

                                    <td data-label="interval">
                                        { item.interval }
                                    </td>

                                    <td data-label="interest_amount">
                                        { item.interest_amount }
                                    </td>

                                    <td data-label="commission_amount">
                                        { item.commission_amount }
                                    </td>

                                    <td data-label="total_amount">
                                        { item.total_amount }
                                    </td>

                                    <td data-label="total_paid_amount">
                                        { item.total_paid_amount }
                                    </td>

                                    <td data-label="penalty_amount">
                                        { item.penalty_amount }
                                    </td>

                                    <td data-label="pending_amount">
                                        { item.pending_amount }
                                    </td>

                                    <td data-label="cross_amount">
                                        { item.cross_amount }
                                    </td>

                                    <td data-label="remark">
                                        { item.remark }
                                    </td>

                                </tr>
                              ))}
                            </tbody>
                        </table>
                        </div>
                        {!loans?.payments_loan?.length && <div className={'text-center py-4'}>No data</div>}
                    </CardBox>
                </>

                <BaseDivider />

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

LoansView.getLayout = function getLayout(page: ReactElement) {
    return (
      <LayoutAuthenticated>
          {page}
      </LayoutAuthenticated>
    )
}

export default LoansView;
