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

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

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Reference</p>
            <p>{reservations?.ref}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>StatusManual</p>
            <p>{reservations?.status_manual ?? 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>StatusComputed</p>
            <p>{reservations?.status_computed ?? 'No data'}</p>
          </div>

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

            <p>{reservations?.client?.first_name ?? 'No data'}</p>
          </div>

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

            <p>{reservations?.vehicle?.plate_number ?? 'No data'}</p>
          </div>

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

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>PickupAddress</p>
            <p>{reservations?.pickup_address}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>ReturnAddress</p>
            <p>{reservations?.return_address}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Options</p>
            <p>{reservations?.options}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Days</p>
            <p>{reservations?.days || 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>PricePerDay</p>
            <p>{reservations?.price_per_day || 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>TotalPrice</p>
            <p>{reservations?.total_price || 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>PaidAmount</p>
            <p>{reservations?.paid_amount || 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>BalanceAmount</p>
            <p>{reservations?.balance_amount || 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>GuaranteeMethod</p>
            <p>{reservations?.guarantee_method ?? 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>GuaranteeAmount</p>
            <p>{reservations?.guarantee_amount || 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>GuaranteeStatus</p>
            <p>{reservations?.guarantee_status ?? 'No data'}</p>
          </div>

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

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Notes</p>
            <p>{reservations?.notes}</p>
          </div>

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

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

          <>
            <p className={'block font-bold mb-2'}>Claims Reservation</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>
                    {reservations.claims_reservation &&
                      Array.isArray(reservations.claims_reservation) &&
                      reservations.claims_reservation.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>
              {!reservations?.claims_reservation?.length && (
                <div className={'text-center py-4'}>No data</div>
              )}
            </CardBox>
          </>

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

                      <th>LicenseNumber</th>

                      <th>LicenseIssueDate</th>

                      <th>IDCopyURL</th>

                      <th>LicenseCopyURL</th>
                    </tr>
                  </thead>
                  <tbody>
                    {reservations.drivers_reservation &&
                      Array.isArray(reservations.drivers_reservation) &&
                      reservations.drivers_reservation.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(`/drivers/drivers-view/?id=${item.id}`)
                          }
                        >
                          <td data-label='full_name'>{item.full_name}</td>

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

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

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

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

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

                      <th>Amount</th>

                      <th>Status</th>

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

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

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

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

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

                      <th>Date</th>

                      <th>Location</th>

                      <th>Amount</th>

                      <th>Status</th>

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

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

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

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

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

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

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

                      <th>Amount</th>

                      <th>PaidAt</th>

                      <th>ReceiptReference</th>

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

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

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

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

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

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

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

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

          <BaseDivider />

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

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

export default ReservationsView;
