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

  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 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'}>Tenant</p>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                      <th>Description</th>

                      <th>Status</th>

                      <th>Attachments</th>
                    </tr>
                  </thead>
                  <tbody>
                    {clients.claims_client &&
                      Array.isArray(clients.claims_client) &&
                      clients.claims_client.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(`/claims/claims-view/?id=${item.id}`)
                          }
                        >
                          <td data-label='category'>{item.category}</td>

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

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

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

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

                      <th>StatusManual</th>

                      <th>StatusComputed</th>

                      <th>StartAt</th>

                      <th>EndAt</th>

                      <th>PickupAddress</th>

                      <th>ReturnAddress</th>

                      <th>Options</th>

                      <th>Days</th>

                      <th>PricePerDay</th>

                      <th>TotalPrice</th>

                      <th>PaidAmount</th>

                      <th>BalanceAmount</th>

                      <th>GuaranteeMethod</th>

                      <th>GuaranteeAmount</th>

                      <th>GuaranteeStatus</th>

                      <th>DepartureValidatedAt</th>

                      <th>ReturnValidatedAt</th>

                      <th>Notes</th>
                    </tr>
                  </thead>
                  <tbody>
                    {clients.reservations_client &&
                      Array.isArray(clients.reservations_client) &&
                      clients.reservations_client.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/reservations/reservations-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='ref'>{item.ref}</td>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                          <td data-label='notes'>{item.notes}</td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
              {!clients?.reservations_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 permission={'READ_CLIENTS'}>
      {page}
    </LayoutAuthenticated>
  );
};

export default ClientsView;
