import * as cacheApi from '@/api/cache/query';
import { min } from '@/styles/mq';
import { useQuery } from '@tanstack/react-query';
import { memo, useState } from 'react';
import styled from 'styled-components';
import { Button, Collapse } from 'ui/elements';
import { Flex } from 'ui/grid';

type QueryProps = {
  readonly handleDeleteQuery: () => Promise<void>;
  readonly queryKey: string;
};

const StyledPre = styled.pre`
  max-height: 300px;
  overflow-y: auto;

  ${min('desktop')} {
    max-height: 800px;
  }
`;

export const Query = memo(({ handleDeleteQuery, queryKey }: QueryProps) => {
  const { data, refetch } = useQuery({
    enabled: false,
    queryFn: ({ signal }) => signal && cacheApi.getQueryValue(queryKey, { signal }),
    queryKey: ['admin', 'cache', 'query', queryKey],
    refetchOnWindowFocus: false,
  });

  const [activeKey, setActiveKey] = useState<string | undefined>(undefined);
  const [deletePending, setDeletePending] = useState(false);

  const content = (
    <>
      <StyledPre>{JSON.stringify(data, null, 2)}</StyledPre>
      <Flex justifyContent="flex-end">
        <Button
          type="primary"
          danger
          disabled={deletePending}
          onClick={() => {
            setDeletePending(true);
            handleDeleteQuery().finally(() => {
              setDeletePending(false);
            });
          }}
        >
          Удалить
        </Button>
      </Flex>
    </>
  );

  return (
    <Collapse
      bordered={false}
      activeKey={activeKey}
      items={[
        {
          children: data ? content : 'Загрузка...',
          key: queryKey,
          label: queryKey,
        },
      ]}
      onChange={() => {
        if (activeKey) {
          setActiveKey(undefined);
        } else {
          setActiveKey(queryKey);

          refetch();
        }
      }}
    />
  );
});
