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;
  page_elements_page?: Array<Record<string, unknown>>;
  page_links_from_page?: Array<Record<string, unknown>>;
  page_links_to_page?: Array<Record<string, unknown>>;
  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>

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

                      <th>Name</th>

                      <th>Sortorder</th>

                      <th>Isvisible</th>

                      <th>X(%)</th>

                      <th>Y(%)</th>

                      <th>Width(%)</th>

                      <th>Height(%)</th>

                      <th>Rotation(deg)</th>

                      <th>StyleJSON</th>

                      <th>ContentJSON</th>
                    </tr>
                  </thead>
                  <tbody>
                    {tour_pages.page_elements_page &&
                      Array.isArray(tour_pages.page_elements_page) &&
                      tour_pages.page_elements_page.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/page_elements/page_elements-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='element_type'>{item.element_type}</td>

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

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

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

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

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

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

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

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

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

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

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

                      <th>ExternalURL</th>

                      <th>Isactive</th>

                      <th>Triggerselector</th>
                    </tr>
                  </thead>
                  <tbody>
                    {tour_pages.page_links_from_page &&
                      Array.isArray(tour_pages.page_links_from_page) &&
                      tour_pages.page_links_from_page.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/page_links/page_links-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='direction'>{item.direction}</td>

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

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

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

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

                      <th>ExternalURL</th>

                      <th>Isactive</th>

                      <th>Triggerselector</th>
                    </tr>
                  </thead>
                  <tbody>
                    {tour_pages.page_links_to_page &&
                      Array.isArray(tour_pages.page_links_to_page) &&
                      tour_pages.page_links_to_page.map((item: any) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/page_links/page_links-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='direction'>{item.direction}</td>

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

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

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

          <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;
