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/projects/projectsSlice';
import type { Project } from '../../types/entities';
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';

// Extended Project type with related entities for view page
interface ProjectWithRelations extends Project {
  logo_url?: string;
  favicon_url?: string;
  og_image_url?: string;
  is_deleted?: boolean;
  deleted_at_time?: string | Date;
  project_memberships_project?: Array<{
    id: string;
    access_level?: string;
    is_active?: boolean;
    invited_at?: string | Date;
    accepted_at?: string | Date;
  }>;
  assets_project?: Array<{
    id: string;
    name?: string;
    asset_type?: string;
    cdn_url?: string;
    storage_key?: string;
    mime_type?: string;
    size_mb?: number;
    width_px?: number;
    height_px?: number;
    duration_sec?: number;
    checksum?: string;
    is_public?: boolean;
    is_deleted?: boolean;
    deleted_at_time?: string | Date;
  }>;
  presigned_url_requests_project?: Array<{
    id: string;
    purpose?: string;
    asset_type?: string;
    requested_key?: string;
    mime_type?: string;
    requested_size_mb?: number;
    expires_at?: string | Date;
    status?: string;
  }>;
  tour_pages_project?: Array<{
    id: string;
    environment?: string;
    source_key?: string;
    name?: string;
    slug?: string;
    sort_order?: number;
    background_image_url?: string;
    background_video_url?: string;
    background_audio_url?: string;
    background_loop?: boolean;
    requires_auth?: boolean;
    ui_schema_json?: string;
  }>;
  project_audio_tracks_project?: Array<{
    id: string;
    environment?: string;
    source_key?: string;
    name?: string;
    slug?: string;
    url?: string;
    loop?: boolean;
    volume?: number;
    sort_order?: number;
    is_enabled?: boolean;
  }>;
  publish_events_project?: Array<{
    id: string;
    from_environment?: string;
    to_environment?: string;
    started_at?: string | Date;
    finished_at?: string | Date;
    status?: string;
    error_message?: string;
    pages_copied?: number;
    transitions_copied?: number;
    audios_copied?: number;
  }>;
  pwa_caches_project?: Array<{
    id: string;
    environment?: string;
    cache_version?: string;
    manifest_json?: string;
    asset_list_json?: string;
    generated_at?: string | Date;
    is_active?: boolean;
  }>;
  access_logs_project?: Array<{
    id: string;
    environment?: string;
    path?: string;
    ip_address?: string;
    user_agent?: string;
    accessed_at?: string | Date;
  }>;
}

const ProjectsView = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const projectsState = useAppSelector((state) => state.projects);
  const projectsData = projectsState.projects as
    | ProjectWithRelations
    | ProjectWithRelations[]
    | undefined;
  const project = Array.isArray(projectsData) ? projectsData[0] : projectsData;

  const { id } = router.query as { id?: string };

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

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

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Description</p>
            {project?.description ? (
              <p>{project.description}</p>
            ) : (
              <p>No data</p>
            )}
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>LogoURL</p>
            <p>{project?.logo_url}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>FaviconURL</p>
            <p>{project?.favicon_url}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>OGImageURL</p>
            <p>{project?.og_image_url}</p>
          </div>

          <FormField label='Isdeleted'>
            <SwitchField
              field={{ name: 'is_deleted', value: project?.is_deleted }}
              form={{ setFieldValue: () => null }}
              disabled
            />
          </FormField>

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

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

                      <th>Isactive</th>

                      <th>Invitedat</th>

                      <th>Acceptedat</th>
                    </tr>
                  </thead>
                  <tbody>
                    {project?.project_memberships_project &&
                      Array.isArray(project.project_memberships_project) &&
                      project.project_memberships_project.map((item) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/project_memberships/project_memberships-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='access_level'>{item.access_level}</td>

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

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

                          <td data-label='accepted_at'>
                            {dataFormatter.dateTimeFormatter(item.accepted_at)}
                          </td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
              {!project?.project_memberships_project?.length && (
                <div className={'text-center py-4'}>No data</div>
              )}
            </CardBox>
          </>

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

                      <th>Assettype</th>

                      <th>CDNURL</th>

                      <th>Storagekey</th>

                      <th>MIMEtype</th>

                      <th>Size(MB)</th>

                      <th>Width(px)</th>

                      <th>Height(px)</th>

                      <th>Duration(sec)</th>

                      <th>Checksum</th>

                      <th>Ispublic</th>

                      <th>Isdeleted</th>

                      <th>Deletedat</th>
                    </tr>
                  </thead>
                  <tbody>
                    {project?.assets_project &&
                      Array.isArray(project.assets_project) &&
                      project.assets_project.map((item) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(`/assets/assets-view/?id=${item.id}`)
                          }
                        >
                          <td data-label='name'>{item.name}</td>

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

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

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

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

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

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

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

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

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

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

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

                          <td data-label='deleted_at_time'>
                            {dataFormatter.dateTimeFormatter(
                              item.deleted_at_time,
                            )}
                          </td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
              {!project?.assets_project?.length && (
                <div className={'text-center py-4'}>No data</div>
              )}
            </CardBox>
          </>

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

                      <th>Assettype</th>

                      <th>Requestedkey</th>

                      <th>MIMEtype</th>

                      <th>Requestedsize(MB)</th>

                      <th>Expiresat</th>

                      <th>Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {project?.presigned_url_requests_project &&
                      Array.isArray(project.presigned_url_requests_project) &&
                      project.presigned_url_requests_project.map((item) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/presigned_url_requests/presigned_url_requests-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='purpose'>{item.purpose}</td>

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

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

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

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

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

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

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

                      <th>Sourcekey</th>

                      <th>Name</th>

                      <th>Slug</th>

                      <th>Sortorder</th>

                      <th>BackgroundimageURL</th>

                      <th>BackgroundvideoURL</th>

                      <th>BackgroundaudioURL</th>

                      <th>Backgroundloop</th>

                      <th>Requiresauth</th>

                      <th>UIschemaJSON</th>
                    </tr>
                  </thead>
                  <tbody>
                    {project?.tour_pages_project &&
                      Array.isArray(project.tour_pages_project) &&
                      project.tour_pages_project.map((item) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/tour_pages/tour_pages-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='environment'>{item.environment}</td>

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

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

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

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

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

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

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

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

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

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

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

                      <th>Sourcekey</th>

                      <th>Name</th>

                      <th>Slug</th>

                      <th>URL</th>

                      <th>Loop</th>

                      <th>Volume</th>

                      <th>Sortorder</th>

                      <th>Isenabled</th>
                    </tr>
                  </thead>
                  <tbody>
                    {project?.project_audio_tracks_project &&
                      Array.isArray(project.project_audio_tracks_project) &&
                      project.project_audio_tracks_project.map((item) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/project_audio_tracks/project_audio_tracks-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='environment'>{item.environment}</td>

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

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

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

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

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

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

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

                          <td data-label='is_enabled'>
                            {dataFormatter.booleanFormatter(item.is_enabled)}
                          </td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
              {!project?.project_audio_tracks_project?.length && (
                <div className={'text-center py-4'}>No data</div>
              )}
            </CardBox>
          </>

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

                      <th>Toenvironment</th>

                      <th>Startedat</th>

                      <th>Finishedat</th>

                      <th>Status</th>

                      <th>Errormessage</th>

                      <th>Pagescopied</th>

                      <th>Transitionscopied</th>

                      <th>Audioscopied</th>
                    </tr>
                  </thead>
                  <tbody>
                    {project?.publish_events_project &&
                      Array.isArray(project.publish_events_project) &&
                      project.publish_events_project.map((item) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/publish_events/publish_events-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='from_environment'>
                            {item.from_environment}
                          </td>

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

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

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

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

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

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

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

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

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

                      <th>Cacheversion</th>

                      <th>ManifestJSON</th>

                      <th>AssetlistJSON</th>

                      <th>Generatedat</th>

                      <th>Isactive</th>
                    </tr>
                  </thead>
                  <tbody>
                    {project?.pwa_caches_project &&
                      Array.isArray(project.pwa_caches_project) &&
                      project.pwa_caches_project.map((item) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/pwa_caches/pwa_caches-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='environment'>{item.environment}</td>

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

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

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

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

                          <td data-label='is_active'>
                            {dataFormatter.booleanFormatter(item.is_active)}
                          </td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
              {!project?.pwa_caches_project?.length && (
                <div className={'text-center py-4'}>No data</div>
              )}
            </CardBox>
          </>

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

                      <th>Path</th>

                      <th>IPaddress</th>

                      <th>Useragent</th>

                      <th>Accessedat</th>
                    </tr>
                  </thead>
                  <tbody>
                    {project?.access_logs_project &&
                      Array.isArray(project.access_logs_project) &&
                      project.access_logs_project.map((item) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/access_logs/access_logs-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='environment'>{item.environment}</td>

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

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

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

                          <td data-label='accessed_at'>
                            {dataFormatter.dateTimeFormatter(item.accessed_at)}
                          </td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
              {!project?.access_logs_project?.length && (
                <div className={'text-center py-4'}>No data</div>
              )}
            </CardBox>
          </>

          <BaseDivider />

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

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

export default ProjectsView;
