import React, { useEffect, useState } from 'react';
import styled from 'styled-components';

import { TableIcon } from '@redocly/theme/icons/TableIcon/TableIcon';
import { CardsIcon } from '@redocly/theme/icons/CardsIcon/CardsIcon';
import { CatalogViewMode } from '@redocly/theme/core/types';

function useViewMode(initialViewMode: CatalogViewMode) {
  const [viewMode, setViewMode] = useState<CatalogViewMode | null>(null);

  useEffect(() => {
    setViewMode(initialViewMode);
  }, [initialViewMode]);

  return viewMode;
}

export type CatalogViewModeToggleProps = {
  viewMode: CatalogViewMode;
  onViewModeChange: (mode: CatalogViewMode) => void;
};

export function CatalogViewModeToggle({
  viewMode: initialViewMode,
  onViewModeChange,
}: CatalogViewModeToggleProps) {
  const viewMode = useViewMode(initialViewMode);

  return (
    <ViewModeToggleWrapper data-component-name="Catalog/CatalogViewModeToggle">
      <ViewModeButton
        className={viewMode === 'table' ? 'active' : ''}
        onClick={() => onViewModeChange('table')}
      >
        <TableIcon size="var(--catalog-view-mode-table-icon-size)" />
      </ViewModeButton>
      <ViewModeButton
        className={viewMode === 'cards' ? 'active' : ''}
        onClick={() => onViewModeChange('cards')}
      >
        <CardsIcon size="var(--catalog-view-mode-cards-icon-size)" />
      </ViewModeButton>
    </ViewModeToggleWrapper>
  );
}

const ViewModeToggleWrapper = styled.div`
  display: flex;
  gap: var(--catalog-view-mode-toggle-gap);
`;

const ViewModeButton = styled.button`
  width: var(--catalog-view-mode-button-width);
  height: var(--catalog-view-mode-button-height);
  background-color: transparent;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--catalog-view-mode-button-border-radius);

  &.active {
    background-color: var(--catalog-view-mode-toggle-active-bg-color);
  }
`;
