import React, { ReactElement, useEffect } from 'react';
import Head from 'next/head';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { fetch } from '../../stores/tour_pages/tour_pagesSlice';
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';
import type { TourPage, Project } from '../../types/entities';

// Extended type for view page with nested relations
type TourPageWithRelations = TourPage & {
  project?: Project | string | null;
  environment?: string;
  source_key?: string;
  name?: string;
  background_image_url?: string;
  background_video_url?: string;
  background_audio_url?: string;
  background_loop?: boolean;
  requires_auth?: boolean;
  ui_schema_json?: string;
};

// Helper to safely get project name
const getProjectName = (
  project: Project | string | null | undefined,
): string => {
  if (!project) return 'No data';
  if (typeof project === 'string') return project;
  return project.name || 'No data';
};

const Tour_pagesView = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const tourPagesState = useAppSelector((state) => state.tour_pages);
  const tour_pages_data = tourPagesState.tour_pages as
    | TourPageWithRelations
    | TourPageWithRelations[]
    | undefined;
  const tour_pages = Array.isArray(tour_pages_data)
    ? tour_pages_data[0]
    : tour_pages_data;

  const { id } = router.query as { id?: string };
  const idStr = Array.isArray(id) ? id[0] : id;

  function removeLastCharacter(str: string): string {
    return str.slice(0, -1);
  }

  useEffect(() => {
    if (idStr) {
      dispatch(fetch({ id: idStr }));
    }
  }, [dispatch, idStr]);

  return (
    <>
      <Head>
        <title>{getPageTitle('View tour_pages')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={removeLastCharacter('View tour_pages')}
          main
        >
          <BaseButton
            color='info'
            label='Edit'
            href={`/tour_pages/tour_pages-edit/?id=${idStr}`}
          />
        </SectionTitleLineWithButton>
        <CardBox>
          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Project</p>

            <p>{getProjectName(tour_pages?.project)}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Environment</p>
            <p>{tour_pages?.environment ?? 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Sourcekey</p>
            <p>{tour_pages?.source_key}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Name</p>
            <p>{tour_pages?.name}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Slug</p>
            <p>{tour_pages?.slug}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Sortorder</p>
            <p>{tour_pages?.sort_order || 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>BackgroundimageURL</p>
            <p>{tour_pages?.background_image_url}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>BackgroundvideoURL</p>
            <p>{tour_pages?.background_video_url}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>BackgroundaudioURL</p>
            <p>{tour_pages?.background_audio_url}</p>
          </div>

          <FormField label='Backgroundloop'>
            <SwitchField
              field={{
                name: 'background_loop',
                value: tour_pages?.background_loop,
              }}
              form={{ setFieldValue: () => null }}
              disabled
            />
          </FormField>

          <FormField label='Requiresauth'>
            <SwitchField
              field={{
                name: 'requires_auth',
                value: tour_pages?.requires_auth,
              }}
              form={{ setFieldValue: () => null }}
              disabled
            />
          </FormField>

          <FormField label='Multi Text' hasTextareaHeight>
            <textarea
              className={'w-full'}
              disabled
              value={tour_pages?.ui_schema_json}
            />
          </FormField>

          <BaseDivider />

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

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

export default Tour_pagesView;
