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/transitions/transitionsSlice';
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 { Transition, Project } from '../../types/entities';

// Extended type for view page with nested relations
type TransitionWithRelations = Transition & {
  project?: Project | string | null;
  page_links_transition?: Array<Record<string, unknown>>;
  environment?: string;
  source_key?: string;
  slug?: string;
  video_url?: string;
  audio_url?: string;
  supports_reverse?: boolean;
  duration_sec?: number;
};

// 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 TransitionsView = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const transitionsState = useAppSelector((state) => state.transitions);
  const transitions_data = transitionsState.transitions as
    | TransitionWithRelations
    | TransitionWithRelations[]
    | undefined;
  const transitions = Array.isArray(transitions_data)
    ? transitions_data[0]
    : transitions_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 transitions')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={removeLastCharacter('View transitions')}
          main
        >
          <BaseButton
            color='info'
            label='Edit'
            href={`/transitions/transitions-edit/?id=${idStr}`}
          />
        </SectionTitleLineWithButton>
        <CardBox>
          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Project</p>

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

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

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

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

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>VideoURL</p>
            <p>{transitions?.video_url}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>AudioURL</p>
            <p>{transitions?.audio_url}</p>
          </div>

          <FormField label='Supportsreverse'>
            <SwitchField
              field={{
                name: 'supports_reverse',
                value: transitions?.supports_reverse,
              }}
              form={{ setFieldValue: () => null }}
              disabled
            />
          </FormField>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Duration(sec)</p>
            <p>{transitions?.duration_sec || 'No data'}</p>
          </div>

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

          <BaseDivider />

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

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

export default TransitionsView;
