import {
  CloseOutlined,
  ExpandOutlined,
  EyeOutlined,
  LinkOutlined,
  ReloadOutlined,
  SaveOutlined,
  ShrinkOutlined,
} from '@ant-design/icons';
import { Alert, Button, Card, Checkbox, Empty, Flex, Input, Space, Spin, Tag, Typography, message } from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { componentSampleEntries, widgetSampleEntries } from '../../app/manifests/samples.manifest';
import { useTokenAccess } from '../../app/main/tokenAccess';
import { buildPlansPath } from '../../app/main/routes';
import { ComponentSamplesLayout } from '../layout/component-sample-gallery';
import { SampleWidgetsLayout } from '../layout/widget-sample-gallery';
import { fetchReleaseReviewBoardItems, updatePlanReleaseReview } from './api';
import { maskNotePreviewByWord } from './noteMasking';
import { isReleasePendingMainItem, normalizeWorkerStatus } from './quickFilters';
import type { PlanItem, PlanReleaseReviewBoardItem, PlanReleaseReviewStatus } from './types';

const { Paragraph, Text, Title } = Typography;
const { TextArea } = Input;

type ReviewMenuTarget = {
  id: string;
  label: string;
  description: string;
  targetType: 'component' | 'widget';
  targetId: string;
};

type ReviewOverlayTarget = ReviewMenuTarget & {
  planItemId: number;
  planLabel: string;
};

type ReleaseReviewFilter = 'all' | 'pending-main' | 'approved' | 'changes-requested';

const RELEASE_REVIEW_FILTER_OPTIONS: Array<{ label: string; value: ReleaseReviewFilter }> = [
  { label: '전체', value: 'all' },
  { label: 'main 대기', value: 'pending-main' },
  { label: '검수완료', value: 'approved' },
  { label: '수정필요', value: 'changes-requested' },
];
const HIDDEN_COMPONENT_IDS = ['search-command-modal', 'window-ui'];

function formatPlanLabel(item: Pick<PlanItem, 'id' | 'workId'>) {
  const normalizedWorkId = item.workId.trim();
  return normalizedWorkId ? `${normalizedWorkId} · #${item.id}` : `#${item.id}`;
}

function formatDateTime(value: string | null | undefined) {
  if (!value) {
    return '미기록';
  }

  return new Date(value).toLocaleString('ko-KR', {
    timeZone: 'Asia/Seoul',
  });
}

function summarizeNote(note: string | null | undefined) {
  if (!note) {
    return '';
  }

  return note.replace(/\s+/g, ' ').trim();
}

function resolveProtectedText(text: string | null | undefined, hasAccess: boolean) {
  const normalizedText = summarizeNote(text);
  return hasAccess ? normalizedText : maskNotePreviewByWord(normalizedText);
}

function normalizeStringArray(value: unknown) {
  return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
}

function getReviewStatusTagColor(status: PlanReleaseReviewStatus) {
  if (status === 'approved') {
    return 'success';
  }

  if (status === 'changes-requested') {
    return 'error';
  }

  if (status === 'reviewing') {
    return 'processing';
  }

  return 'default';
}

function getReviewStatusLabel(status: PlanReleaseReviewStatus) {
  if (status === 'approved') {
    return '검수완료';
  }

  if (status === 'changes-requested') {
    return '수정필요';
  }

  if (status === 'reviewing') {
    return '검수중';
  }

  return '미검수';
}

function matchesReleaseReviewFilter(item: PlanReleaseReviewBoardItem, filter: ReleaseReviewFilter) {
  if (filter === 'pending-main') {
    return isReleasePendingMainItem(item.planItem);
  }

  if (filter === 'approved') {
    return item.review.status === 'approved';
  }

  if (filter === 'changes-requested') {
    return item.review.status === 'changes-requested';
  }

  return true;
}

function buildPlanPath(section: 'release-review' | 'release', item: Pick<PlanItem, 'id' | 'workId'>) {
  const params = new URLSearchParams();
  params.set('planId', String(item.id));

  if (item.workId.trim()) {
    params.set('workId', item.workId.trim());
  }

  return `${buildPlansPath(section)}?${params.toString()}`;
}

function buildRelatedMenuTargets(item: PlanReleaseReviewBoardItem) {
  const componentTargets = normalizeStringArray(item.review.metadata.componentIds).map(
    (componentId) =>
      ({
        id: `component:${componentId}`,
        label: `컴포넌트 · ${componentId}`,
        description: '이번 자동화에서 개발된 컴포넌트 샘플만 바로 확인합니다.',
        targetType: 'component',
        targetId: componentId,
      }) satisfies ReviewMenuTarget,
  );
  const widgetTargets = normalizeStringArray(item.review.metadata.widgetIds).map(
    (widgetId) =>
      ({
        id: `widget:${widgetId}`,
        label: `위젯 · ${widgetId}`,
        description: '이번 자동화에서 개발된 위젯 샘플만 바로 확인합니다.',
        targetType: 'widget',
        targetId: widgetId,
      }) satisfies ReviewMenuTarget,
  );

  return [...componentTargets, ...widgetTargets];
}

function buildCheckedMenuIds(item: PlanReleaseReviewBoardItem) {
  return new Set(normalizeStringArray(item.review.metadata.checkedPageSelectionIds));
}

function deriveReviewStatus(args: {
  checkedIds: string[];
  targetIds: string[];
  reviewNote: string;
  currentStatus: PlanReleaseReviewStatus;
}) {
  if (args.currentStatus === 'changes-requested' && args.checkedIds.length < args.targetIds.length) {
    return 'changes-requested';
  }

  if (args.targetIds.length > 0 && args.checkedIds.length === args.targetIds.length) {
    return 'approved';
  }

  if (args.checkedIds.length > 0 || args.reviewNote.trim()) {
    return 'reviewing';
  }

  return 'pending';
}

export function ReleaseReviewPage() {
  const { hasAccess } = useTokenAccess();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [messageApi, contextHolder] = message.useMessage();
  const [items, setItems] = useState<PlanReleaseReviewBoardItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [filter, setFilter] = useState<ReleaseReviewFilter>('pending-main');
  const [reviewNoteDrafts, setReviewNoteDrafts] = useState<Record<number, string>>({});
  const [savingByPlanId, setSavingByPlanId] = useState<Record<number, boolean>>({});
  const [overlayTarget, setOverlayTarget] = useState<ReviewOverlayTarget | null>(null);
  const [overlayMinimized, setOverlayMinimized] = useState(false);
  const cardRefs = useRef<Record<number, HTMLDivElement | null>>({});

  const selectedPlanId = useMemo(() => {
    const value = Number(searchParams.get('planId'));
    return Number.isFinite(value) ? value : null;
  }, [searchParams]);

  const selectedWorkId = useMemo(() => {
    const value = searchParams.get('workId')?.trim();
    return value ? value : null;
  }, [searchParams]);

  async function loadReleaseReviews(cancelledRef?: { current: boolean }) {
    setLoading(true);
    setErrorMessage(null);

    try {
      const nextItems = await fetchReleaseReviewBoardItems();

      if (cancelledRef?.current) {
        return;
      }

      setItems(nextItems);
      setReviewNoteDrafts(
        Object.fromEntries(nextItems.map((item) => [item.planItem.id, item.review.reviewNote ?? ''])),
      );
    } catch (error) {
      if (cancelledRef?.current) {
        return;
      }

      setErrorMessage(error instanceof Error ? error.message : 'release 검수 목록을 불러오지 못했습니다.');
    } finally {
      if (!cancelledRef?.current) {
        setLoading(false);
      }
    }
  }

  useEffect(() => {
    const cancelledRef = { current: false };
    void loadReleaseReviews(cancelledRef);

    return () => {
      cancelledRef.current = true;
    };
  }, []);

  const filteredItems = useMemo(() => {
    const keyword = searchKeyword.trim().toLocaleLowerCase('ko-KR');

    return items
      .filter((item) => matchesReleaseReviewFilter(item, filter))
      .filter((item) => {
        if (!keyword) {
          return true;
        }

        try {
          const relatedTargets = buildRelatedMenuTargets(item);
          const searchable = [
            item.planItem.workId,
            item.planItem.note,
            item.planItem.status,
            item.planItem.workerStatus,
            item.planItem.assignedBranch,
            item.review.reviewNote,
            item.review.metadata.summary,
            item.latestSourceWork?.summary,
            ...relatedTargets.flatMap((target) => [target.label, target.description]),
            ...normalizeStringArray(item.latestSourceWork?.changedFiles),
          ]
            .filter(Boolean)
            .join(' ')
            .toLocaleLowerCase('ko-KR');

          return searchable.includes(keyword);
        } catch (error) {
          console.error('release review search filter failed', item.planItem.id, error);
          return false;
        }
      });
  }, [filter, items, searchKeyword]);

  const highlightedPlanId = useMemo(() => {
    if (selectedPlanId) {
      return selectedPlanId;
    }

    if (!selectedWorkId) {
      return null;
    }

    return items.find((item) => item.planItem.workId.trim() === selectedWorkId)?.planItem.id ?? null;
  }, [items, selectedPlanId, selectedWorkId]);

  useEffect(() => {
    if (!highlightedPlanId) {
      return;
    }

    cardRefs.current[highlightedPlanId]?.scrollIntoView({
      behavior: 'smooth',
      block: 'start',
    });
  }, [filteredItems, highlightedPlanId]);

  function patchReview(
    planItemId: number,
    updater: (current: PlanReleaseReviewBoardItem) => PlanReleaseReviewBoardItem,
  ) {
    setItems((previous) => previous.map((item) => (item.planItem.id === planItemId ? updater(item) : item)));
  }

  async function handleSaveReview(
    planItemId: number,
    payload: {
      status?: PlanReleaseReviewStatus;
      reviewNote?: string;
      metadata?: PlanReleaseReviewBoardItem['review']['metadata'];
    },
    successMessage: string,
  ) {
    setSavingByPlanId((previous) => ({
      ...previous,
      [planItemId]: true,
    }));

    try {
      const review = await updatePlanReleaseReview(planItemId, payload);
      patchReview(planItemId, (current) => ({
        ...current,
        review: {
          ...review,
          metadata: {
            ...current.review.metadata,
            ...review.metadata,
          },
        },
      }));
      setReviewNoteDrafts((previous) => ({
        ...previous,
        [planItemId]: review.reviewNote ?? '',
      }));
      messageApi.success(successMessage);
    } catch (error) {
      messageApi.error(error instanceof Error ? error.message : '검수 정보 저장에 실패했습니다.');
    } finally {
      setSavingByPlanId((previous) => ({
        ...previous,
        [planItemId]: false,
      }));
    }
  }

  async function handleCopyLink(path: string) {
    try {
      await navigator.clipboard.writeText(`${window.location.origin}${path}`);
      messageApi.success('링크를 복사했습니다.');
    } catch {
      messageApi.error('링크 복사에 실패했습니다.');
    }
  }

  function handleOpenOverlay(target: ReviewMenuTarget, item: PlanReleaseReviewBoardItem) {
    setOverlayTarget({
      ...target,
      planItemId: item.planItem.id,
      planLabel: formatPlanLabel(item.planItem),
    });
    setOverlayMinimized(false);
  }

  return (
    <div className="release-review-page">
      {contextHolder}
      <Space direction="vertical" size={16} className="release-review-page__stack">
        <Flex align="center" justify="space-between" gap={12} wrap>
          <div>
            <Title level={4} className="release-review-page__title">
              release 검수 보드
            </Title>
            <Paragraph type="secondary" className="release-review-page__copy">
              관련 메뉴를 한 줄씩 확인하고, 필요한 화면만 내부 전체화면으로 열어 최소화/최대화하며 검수할 수 있습니다.
            </Paragraph>
          </div>
          <Space wrap>
            <Button disabled={!hasAccess} onClick={() => navigate(buildPlansPath('release'))}>
              main 대기 목록
            </Button>
            <Button
              onClick={() => {
                void loadReleaseReviews();
              }}
              icon={<ReloadOutlined />}
            >
              새로고침
            </Button>
          </Space>
        </Flex>

        <Alert
          type={hasAccess ? 'info' : 'warning'}
          showIcon
          message={
            hasAccess
              ? '관련 메뉴는 내부 전체화면으로 열리며, 체크박스는 서버에 저장됩니다.'
              : '권한 토큰이 없어 release 검수 보드는 조회만 사용할 수 있습니다.'
          }
          description={
            hasAccess
              ? undefined
              : '새로고침 외 버튼과 입력은 비활성화되며, 요청/메모 내용은 40% 마스킹으로 표시됩니다.'
          }
        />

        <Flex gap={12} wrap className="release-review-page__toolbar">
          <Input.Search
            allowClear
            placeholder="작업 ID, 검수 메모, 관련 메뉴 설명, 변경 파일로 검색"
            value={searchKeyword}
            disabled={!hasAccess}
            onChange={(event) => {
              setSearchKeyword(event.target.value);
            }}
            className="release-review-page__search"
          />
          <Space.Compact>
            {RELEASE_REVIEW_FILTER_OPTIONS.map((option) => (
              <Button
                key={option.value}
                type={filter === option.value ? 'primary' : 'default'}
                disabled={!hasAccess}
                onClick={() => {
                  setFilter(option.value);
                }}
              >
                {option.label}
              </Button>
            ))}
          </Space.Compact>
        </Flex>

        {errorMessage ? <Alert type="error" showIcon message={errorMessage} /> : null}

        {loading ? (
          <div className="release-review-page__loading">
            <Spin />
          </div>
        ) : filteredItems.length === 0 ? (
          <Empty description="release 검수 대상이 없습니다." />
        ) : (
          <div className="release-review-page__grid">
            {filteredItems.map((item) => {
              const planItem = item.planItem;
              const detailPath = buildPlanPath('release', planItem);
              const reviewPath = buildPlanPath('release-review', planItem);
              const previewUrl = item.latestSourceWork?.previewUrl ?? null;
              const changedFiles = item.latestSourceWork?.changedFiles?.slice(0, 8) ?? [];
              const isSaving = Boolean(savingByPlanId[planItem.id]);
              const reviewNoteDraft = reviewNoteDrafts[planItem.id] ?? '';
              const relatedMenuTargets = buildRelatedMenuTargets(item);
              const checkedMenuIds = buildCheckedMenuIds(item);
              const checkedCount = relatedMenuTargets.filter((target) => checkedMenuIds.has(target.id)).length;

              return (
                <div
                  key={planItem.id}
                  ref={(node) => {
                    cardRefs.current[planItem.id] = node;
                  }}
                  className={
                    highlightedPlanId === planItem.id
                      ? 'release-review-page__card-shell release-review-page__card-shell--selected'
                      : 'release-review-page__card-shell'
                  }
                >
                  <Card
                    size="small"
                    className="release-review-page__card"
                    title={
                      <Space size={[8, 8]} wrap>
                        <Text strong>{formatPlanLabel(planItem)}</Text>
                        <Tag color={planItem.status === '완료' ? 'success' : 'geekblue'}>{planItem.status}</Tag>
                        {planItem.workerStatus ? (
                          <Tag color={normalizeWorkerStatus(planItem.workerStatus).includes('실패') ? 'error' : 'gold'}>
                            {planItem.workerStatus}
                          </Tag>
                        ) : null}
                        <Tag color={getReviewStatusTagColor(item.review.status)}>{getReviewStatusLabel(item.review.status)}</Tag>
                        <Tag>{`메뉴 ${checkedCount}/${relatedMenuTargets.length}`}</Tag>
                      </Space>
                    }
                    extra={<Text type="secondary">{formatDateTime(planItem.updatedAt)}</Text>}
                  >
                    <Space direction="vertical" size={12} className="release-review-page__card-body">
                      <div>
                        <Text strong>검수 요약</Text>
                        <Paragraph className="release-review-page__summary" ellipsis={{ rows: 3, expandable: true, symbol: '더보기' }}>
                          {resolveProtectedText(item.review.metadata.summary || planItem.note, hasAccess)}
                        </Paragraph>
                        <Paragraph className="release-review-page__history-summary" ellipsis={{ rows: 2, expandable: true, symbol: '더보기' }}>
                          원본 요청: {resolveProtectedText(planItem.note, hasAccess)}
                        </Paragraph>
                      </div>

                      <Space size={[8, 8]} wrap>
                        {planItem.assignedBranch ? <Tag>{planItem.assignedBranch}</Tag> : null}
                        {planItem.releaseTarget ? <Tag color="blue">{planItem.releaseTarget}</Tag> : null}
                        {planItem.autoDeployToMain ? <Tag color="green">main 자동반영</Tag> : <Tag>main 수동반영</Tag>}
                        {previewUrl ? <Tag color="purple">Preview 연결됨</Tag> : <Tag>Preview 없음</Tag>}
                      </Space>

                      <Flex gap={8} wrap>
                        <Button
                          type="primary"
                          icon={<EyeOutlined />}
                          disabled={!hasAccess}
                          onClick={() => {
                            navigate(detailPath);
                          }}
                        >
                          자동화 상세
                        </Button>
                        <Button
                          icon={<LinkOutlined />}
                          disabled={!hasAccess}
                          onClick={() => {
                            void handleCopyLink(reviewPath);
                          }}
                        >
                          검수 링크
                        </Button>
                        <Button
                          href={previewUrl ?? undefined}
                          target="_blank"
                          rel="noreferrer"
                          disabled={!hasAccess || !previewUrl}
                        >
                          Preview
                        </Button>
                        <Button
                          danger
                          disabled={!hasAccess || isSaving}
                          onClick={() => {
                            void handleSaveReview(
                              planItem.id,
                              {
                                status: 'changes-requested',
                                reviewNote: reviewNoteDraft,
                                metadata: item.review.metadata,
                              },
                              '검수 상태를 수정필요로 저장했습니다.',
                            );
                          }}
                        >
                          수정 필요
                        </Button>
                      </Flex>

                      <div className="release-review-page__menu-section">
                        <Text strong>관련 메뉴 체크</Text>
                        {relatedMenuTargets.length ? (
                          <div className="release-review-page__menu-list">
                            {relatedMenuTargets.map((target) => {
                              const checked = checkedMenuIds.has(target.id);

                              return (
                                <div key={`${planItem.id}:${target.id}`} className="release-review-page__menu-item">
                                  <Checkbox
                                    checked={checked}
                                    disabled={!hasAccess || isSaving}
                                    onChange={(event) => {
                                      const nextCheckedIds = relatedMenuTargets
                                        .map((menuTarget) => menuTarget.id)
                                        .filter((menuTargetId) =>
                                          menuTargetId === target.id ? event.target.checked : checkedMenuIds.has(menuTargetId),
                                        );

                                      void handleSaveReview(
                                        planItem.id,
                                        {
                                          reviewNote: reviewNoteDraft,
                                          status: deriveReviewStatus({
                                            checkedIds: nextCheckedIds,
                                            targetIds: relatedMenuTargets.map((menuTarget) => menuTarget.id),
                                            reviewNote: reviewNoteDraft,
                                            currentStatus: item.review.status,
                                          }),
                                          metadata: {
                                            ...item.review.metadata,
                                            checkedPageSelectionIds: nextCheckedIds,
                                          },
                                        },
                                        event.target.checked
                                          ? `${target.label} 검수를 체크했습니다.`
                                          : `${target.label} 검수를 해제했습니다.`,
                                      );
                                    }}
                                  >
                                    <span className="release-review-page__menu-label">{target.label}</span>
                                  </Checkbox>
                                  <Text type="secondary" className="release-review-page__menu-description">
                                    {target.description}
                                  </Text>
                                  <Button
                                    size="small"
                                    disabled={!hasAccess}
                                    onClick={() => {
                                      handleOpenOverlay(target, item);
                                    }}
                                  >
                                    전체화면 열기
                                  </Button>
                                </div>
                              );
                            })}
                          </div>
                        ) : (
                          <Paragraph className="release-review-page__empty-copy" type="secondary">
                            연결된 관련 메뉴가 아직 없습니다.
                          </Paragraph>
                        )}
                      </div>

                      <div className="release-review-page__memo">
                        <Text strong>검수 메모</Text>
                        <TextArea
                          rows={3}
                          value={hasAccess ? reviewNoteDraft : maskNotePreviewByWord(reviewNoteDraft)}
                          placeholder="확인 결과나 수정 필요 사항을 남기세요."
                          disabled={!hasAccess}
                          onChange={(event) => {
                            setReviewNoteDrafts((previous) => ({
                              ...previous,
                              [planItem.id]: event.target.value,
                            }));
                          }}
                        />
                        <Flex justify="space-between" align="center" gap={8} wrap>
                          <Text type="secondary">
                            확인자 {item.review.checkedByNickname ?? item.review.checkedByClientId ?? '미기록'} · {formatDateTime(item.review.checkedAt)}
                          </Text>
                          <Button
                            type="primary"
                            icon={<SaveOutlined />}
                            loading={isSaving}
                            disabled={!hasAccess}
                            onClick={() => {
                              void handleSaveReview(
                                planItem.id,
                                {
                                  reviewNote: reviewNoteDraft,
                                  status: deriveReviewStatus({
                                    checkedIds: Array.from(checkedMenuIds),
                                    targetIds: relatedMenuTargets.map((target) => target.id),
                                    reviewNote: reviewNoteDraft,
                                    currentStatus: item.review.status,
                                  }),
                                  metadata: item.review.metadata,
                                },
                                '검수 메모를 저장했습니다.',
                              );
                            }}
                          >
                            메모 저장
                          </Button>
                        </Flex>
                      </div>

                      {item.latestSourceWork ? (
                        <Space direction="vertical" size={8} className="release-review-page__history">
                          <Flex gap={8} wrap>
                            <Text type="secondary">최근 작업란: {formatDateTime(item.latestSourceWork.createdAt)}</Text>
                            <Text type="secondary">브랜치 {item.latestSourceWork.branchName}</Text>
                          </Flex>
                          <Paragraph className="release-review-page__history-summary" ellipsis={{ rows: 2, expandable: true, symbol: '더보기' }}>
                            {resolveProtectedText(item.latestSourceWork.summary, hasAccess)}
                          </Paragraph>
                        </Space>
                      ) : (
                        <Text type="secondary">연결된 source work 기록이 없습니다.</Text>
                      )}

                      <div>
                        <Text strong>검수 대상 파일</Text>
                        {changedFiles.length ? (
                          <Space size={[6, 6]} wrap className="release-review-page__target-tags">
                            {changedFiles.map((file) => (
                              <Tag key={`${planItem.id}:${file}`}>{file}</Tag>
                            ))}
                          </Space>
                        ) : (
                          <Paragraph className="release-review-page__empty-copy" type="secondary">
                            최근 기록에 남은 변경 파일이 없습니다.
                          </Paragraph>
                        )}
                      </div>
                    </Space>
                  </Card>
                </div>
              );
            })}
          </div>
        )}
      </Space>

      {overlayTarget ? (
        <div
          className={`release-review-page__overlay${
            overlayMinimized ? ' release-review-page__overlay--minimized' : ''
          }`}
        >
          <Card
            bordered={false}
            className={`release-review-page__overlay-card${
              overlayMinimized ? ' release-review-page__overlay-card--minimized' : ''
            }`}
            title={
              <div className="release-review-page__overlay-title-row">
                <div className="release-review-page__overlay-title-copy">
                  <Text strong>{overlayTarget.label}</Text>
                  <Text type="secondary">
                    {overlayTarget.planLabel} · {overlayTarget.description}
                  </Text>
                </div>
                <Space size={8}>
                  <Button
                    type="text"
                    aria-label={overlayMinimized ? '전체화면으로 확장' : '최소화'}
                    icon={overlayMinimized ? <ExpandOutlined /> : <ShrinkOutlined />}
                    onClick={() => {
                      setOverlayMinimized((previous) => !previous);
                    }}
                  />
                  <Button
                    type="text"
                    aria-label="닫기"
                    icon={<CloseOutlined />}
                    onClick={() => {
                      setOverlayTarget(null);
                      setOverlayMinimized(false);
                    }}
                  />
                </Space>
              </div>
            }
          >
            {overlayMinimized ? (
              <Text type="secondary">헤더 아이콘으로 다시 최대화할 수 있습니다.</Text>
            ) : overlayTarget.targetType === 'component' ? (
              <div className="release-review-page__overlay-content">
                <ComponentSamplesLayout
                  entries={componentSampleEntries}
                  excludeComponentIds={HIDDEN_COMPONENT_IDS}
                  includeComponentIds={[overlayTarget.targetId]}
                />
              </div>
            ) : (
              <div className="release-review-page__overlay-content">
                <SampleWidgetsLayout entries={widgetSampleEntries} includeComponentIds={[overlayTarget.targetId]} />
              </div>
            )}
          </Card>
        </div>
      ) : null}
    </div>
  );
}
