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/clients/clientsSlice'
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 ClientsView = () => {
    const router = useRouter()
    const dispatch = useAppDispatch()
    const { clients } = useAppSelector((state) => state.clients)

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

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

                <div className={'mb-4'}>
                    <p className={'block font-bold mb-2'}>NameEN</p>
                    <p>{clients?.name_en}</p>
                </div>

                <div className={'mb-4'}>
                    <p className={'block font-bold mb-2'}>NameKH</p>
                    <p>{clients?.name_kh}</p>
                </div>

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

                <div className={'mb-4'}>
                    <p className={'block font-bold mb-2'}>PhoneNumber</p>
                    <p>{clients?.phone_number}</p>
                </div>

                <FormField label='IsNew'>
                    <SwitchField
                      field={{name: 'is_new', value: clients?.is_new}}
                      form={{setFieldValue: () => null}}
                      disabled
                    />
                </FormField>

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

                        <p>{clients?.document_type?.name ?? 'No data'}</p>

                </div>

                <div className={'mb-4'}>
                    <p className={'block font-bold mb-2'}>DocumentNumber</p>
                    <p>{clients?.document_number}</p>
                </div>

                <div className={'mb-4'}>
                    <p className={'block font-bold mb-2'}>Sex</p>
                    <p>{clients?.sex ?? 'No data'}</p>
                </div>

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

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

                </div>

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

                        <p>{clients?.user?.firstName ?? 'No data'}</p>

                </div>

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

                        <p>{clients?.province?.name_en ?? 'No data'}</p>

                </div>

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

                        <p>{clients?.district?.name_en ?? 'No data'}</p>

                </div>

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

                        <p>{clients?.commune?.name_en ?? 'No data'}</p>

                </div>

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

                        <p>{clients?.village?.name_en ?? 'No data'}</p>

                </div>

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

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

                </div>

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

                                <th>Code</th>

                                <th>PrincipalAmount</th>

                                <th>Term</th>

                                <th>PendingAmount</th>

                                <th>LastPendingAmount</th>

                                <th>Rate</th>

                                <th>CommissionRate</th>

                                <th>RegistrationDate</th>

                                <th>StartedPaymentDate</th>

                                <th>LastPaymentDate</th>

                                <th>FinishPaymentDate</th>

                                <th>FinishDiscount</th>

                                <th>FinishDiscountAmount</th>

                                <th>AdminRate</th>

                                <th>AdminAmount</th>

                                <th>Purpose</th>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                <BaseDivider />

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

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

export default ClientsView;
