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/assets/assetsSlice';
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 type { Asset, AssetVariant } from '../../types/entities';

// Extended type to handle asset variants from API (includes size_mb not in base type)
interface AssetVariantWithSize extends AssetVariant {
  size_mb?: number;
}

// Extended type to handle asset variants relation from API
interface AssetWithVariants extends Asset {
  asset_variants_asset?: AssetVariantWithSize[];
}

const AssetsView = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const assetsState = useAppSelector((state) => state.assets);
  const assets = assetsState.assets as
    | AssetWithVariants
    | AssetWithVariants[]
    | undefined;
  const asset = Array.isArray(assets) ? assets[0] : assets;

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

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

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

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

            <p>
              {typeof asset?.project === 'object' && asset?.project
                ? asset.project.name
                : 'No data'}
            </p>
          </div>

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Asset format</p>
            <p>{asset?.asset_type ?? 'No data'}</p>
          </div>
          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Type</p>
            <p>{asset?.type ?? 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>CDNURL</p>
            <p>{asset?.cdn_url}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Storagekey</p>
            <p>{asset?.storage_key}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>MIMEtype</p>
            <p>{asset?.mime_type}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Size(MB)</p>
            <p>{asset?.size_mb || 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Width(px)</p>
            <p>{asset?.width_px || 'No data'}</p>
          </div>

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Height(px)</p>
            <p>{asset?.height_px || 'No data'}</p>
          </div>

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

          <div className={'mb-4'}>
            <p className={'block font-bold mb-2'}>Checksum</p>
            <p>{asset?.checksum}</p>
          </div>

          <FormField label='Ispublic'>
            <SwitchField
              field={{ name: 'is_public', value: asset?.is_public }}
              form={{ setFieldValue: () => null }}
              disabled
            />
          </FormField>

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

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

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

                      <th>CDNURL</th>

                      <th>Width(px)</th>

                      <th>Height(px)</th>

                      <th>Size(MB)</th>
                    </tr>
                  </thead>
                  <tbody>
                    {asset?.asset_variants_asset &&
                      Array.isArray(asset.asset_variants_asset) &&
                      asset.asset_variants_asset.map((item) => (
                        <tr
                          key={item.id}
                          onClick={() =>
                            router.push(
                              `/asset_variants/asset_variants-view/?id=${item.id}`,
                            )
                          }
                        >
                          <td data-label='variant_type'>{item.variant_type}</td>

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

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

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

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

          <BaseDivider />

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

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

export default AssetsView;
