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

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

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>PlateNumber</p>
            <p>{vehicles?.plate_number}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Brand</p>
            <p>{vehicles?.brand}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Model</p>
            <p>{vehicles?.model}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Year</p>
            <p>{vehicles?.year || 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Color</p>
            <p>{vehicles?.color}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Category</p>
            <p>{vehicles?.category ?? 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>FuelType</p>
            <p>{vehicles?.fuel_type ?? 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Transmission</p>
            <p>{vehicles?.transmission ?? 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Mileage</p>
            <p>{vehicles?.mileage || 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>DailyPrice</p>
            <p>{vehicles?.daily_price || 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Status</p>
            <p>{vehicles?.status ?? 'No data'}</p>
          </div>

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

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Photos</p>
            <p>{vehicles?.photos}</p>
          </div>

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

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

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

                      <th>Category</th>

                      <th>Amount</th>

                      <th>Date</th>

                      <th>Note</th>

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

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

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

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

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

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

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

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

                      <th>ScheduledAt</th>

                      <th>Odometer</th>

                      <th>Cost</th>

                      <th>Notes</th>

                      <th>Attachments</th>
                    </tr>
                  </thead>
                  <tbody>
                    {vehicles.maintenance_vehicle &&
                      Array.isArray(vehicles.maintenance_vehicle) &&
                      vehicles.maintenance_vehicle.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/maintenance/maintenance-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='type'>{item.type}</td>

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

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

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

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

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

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

          <BaseDivider />

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

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

export default VehiclesView;
