import clsx from 'clsx';
import React from 'react';
import { twMerge } from 'tailwind-merge';

import { formatDuration } from '@/components/song/songUtils';
import { formatDate } from '@/utils/utils';

import { HookStaffReviewStatus, HooksFeedType } from './constants';
import { VideoHookEntity } from './useVideoHooks';

export type NerdModeOverlayProps = {
  hook: VideoHookEntity;
  index: number;
  downlink?: number;
  maxResolution: number;
  videoElementSlotIndex?: number;
  hookCount?: number;
  feedId?: HooksFeedType;
  hookId?: string;
  userHandle?: string;
  feedCurrentHookId?: string;
};

export type Props = NerdModeOverlayProps &
  Omit<React.HTMLAttributes<HTMLDivElement>, keyof NerdModeOverlayProps>;

const NerdModeOverlay: React.FC<Props> = ({
  className,
  hook,
  index,
  downlink,
  maxResolution,
  videoElementSlotIndex,
  hookCount,
  feedId,
  hookId,
  userHandle,
  feedCurrentHookId,
  ...restProps
}) => (
  <div
    className={twMerge(
      'max-w-full min-w-144 rounded-lg bg-background-dark-overlay p-3 text-foreground-primary-glass backdrop-blur-md',
      className
    )}
    {...restProps}
  >
    <dl
      className={clsx(
        'grid grid-cols-[minmax(12rem,auto)_1fr] gap-1 gap-x-4 font-mono text-xs',
        '[&>div]:col-span-full [&>div]:grid [&>div]:grid-cols-subgrid [&>div]:gap-[inherit]',
        '[&>div:not(:last-child)]:border-b [&>div:not(:last-child)]:border-border-primary [&>div:not(:last-child)]:pb-1',
        '[&_h4]:col-span-full [&_h4]:font-bold [&_h4]:text-white [&_h4]:underline',
        '[&_dt]:text-foreground-secondary-glass'
      )}
    >
      <div>
        <h4>Context</h4>
        <dt>Feed ID</dt>
        <dd>{feedId ?? '--'}</dd>
        <dt>Hook ID</dt>
        <dd>{hookId ?? '--'}</dd>
        <dt>User Handle</dt>
        <dd>{userHandle ?? '--'}</dd>
        <dt>Feed Current Hook ID</dt>
        <dd>{feedCurrentHookId ?? '--'}</dd>
      </div>
      <div>
        <h4>Hook</h4>
        <dt>Index</dt>
        <dd>{`${index} / ${hookCount}`}</dd>
        <dt>Hook ID</dt>
        <dd>{hook.id}</dd>
        <dt>Creator</dt>
        <dd>{hook.user?.handle || 'N/A'}</dd>
        <dt>Creation Time</dt>
        <dd>{formatDate(new Date(hook.createdAt))}</dd>
        <dt>Duration</dt>
        <dd>{formatDuration(hook.videoDuration, false, true)}</dd>
        <dt>Creation Source</dt>
        <dd>
          {hook.creationSource === 'user_upload'
            ? 'User Upload'
            : hook.creationSource === 'backfill_video_cover'
              ? 'Backfill Video Cover'
              : 'Unknown'}
        </dd>
      </div>
      <div>
        <h4>Clip</h4>
        <dt>Clip ID</dt>
        <dd>{hook.originalClipId}</dd>
        <dt>Clip Start</dt>
        <dd>{formatDuration(hook.startClipTimestamp, false, true)}</dd>
        <dt>Clip End</dt>
        <dd>{formatDuration(hook.endClipTimestamp, false, true)}</dd>
      </div>
      <div>
        <h4>Video</h4>
        {videoElementSlotIndex !== undefined && (
          <>
            <dt>Video Slot:</dt>
            <dd>{videoElementSlotIndex}</dd>
          </>
        )}
        <dt>Bandwidth</dt>
        <dd>{downlink?.toFixed(1) || 'N/A'} Mbps</dd>
        <dt>Max Resolution</dt>
        <dd>{maxResolution}p</dd>
        {hook.videoStreamingResolutions && (
          <>
            <dt>Resolutions</dt>
            <dd>
              {hook.videoStreamingResolutions
                .map((r) => `${r.resolution}p`)
                .join(', ')}
            </dd>
          </>
        )}
      </div>
      <div>
        <h4>Metadata</h4>
        <dt>Is Test</dt>
        <dd className={clsx({ 'text-accent-yellow': hook.isTest })}>
          {hook.isTest ? 'YES' : 'NO'}
        </dd>
        <dt>Review Status:</dt>
        <dd
          className={clsx({
            'text-accent-error-on-primary':
              hook.staffReviewStatus === HookStaffReviewStatus.Flagged,
            'text-accent-success-on-primary':
              hook.staffReviewStatus === HookStaffReviewStatus.Approved,
          })}
        >
          {hook.staffReviewStatus === HookStaffReviewStatus.Flagged
            ? 'FLAGGED'
            : hook.staffReviewStatus === HookStaffReviewStatus.Approved
              ? 'APPROVED'
              : 'UNREVIEWED'}
        </dd>
        <dt>Recommendation Run ID</dt>
        <dd>
          {hook.recommendationRunId ? (
            hook.recommendationRunId.startsWith('modal-') ? (
              <a
                href={`https://hooks-recs.suno.run/?request_id=${hook.recommendationRunId}`}
                target='_blank'
                rel='noopener noreferrer'
              >
                {hook.recommendationRunId}
              </a>
            ) : (
              hook.recommendationRunId
            )
          ) : (
            '(none)'
          )}
        </dd>
      </div>
    </dl>
  </div>
);

export default NerdModeOverlay;
