import Background from '../Layout/Background';
import * as cacheApi from '@/api/cache/query';
import { min } from '@/styles/mq';
import { useQuery } from '@tanstack/react-query';
import { memo, useMemo, useState } from 'react';
import type { QueryItem } from 'shared/types/cache';
import styled from 'styled-components';
import { Button, Collapse, Divider } from 'ui/elements';
import { Flex } from 'ui/grid';

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

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

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 content = (
    <>
      <StyledPre>{JSON.stringify(data, null, 2)}</StyledPre>
      <Flex justifyContent="flex-end">
        <Button type="primary" danger onClick={handleDeleteQuery}>
          Удалить
        </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();
        }
      }}
    />
  );
});

type QueryListProps = QueryItem;

const QueryList = memo(({ queries }: QueryListProps) => {
  const [deletedQueries, setDeletedQueries] = useState<QueryItem['queries']>([]);

  const activeQueries = useMemo(
    () => queries.filter((queryKey) => !deletedQueries.includes(queryKey)),
    [deletedQueries, queries]
  );

  function deleteQuery(queryKey: string) {
    cacheApi.deleteQuery(queryKey).then(() => setDeletedQueries([...deletedQueries, queryKey]));
  }

  return activeQueries.map((queryKey) => (
    <Query
      key={queryKey}
      queryKey={queryKey}
      handleDeleteQuery={() => {
        deleteQuery(queryKey);
      }}
    />
  ));
});

const Wrapper = styled(Background)`
  padding: 4px 6px;
  width: 100%;

  ${min('tablet')} {
    min-height: 790px;
  }

  ${min('laptop')} {
    padding: 4px 6px 10px;
    width: 1024px;
  }
`;

export function CacheQueries() {
  const { data: queries } = useQuery({
    enabled: false,
    queryFn: ({ signal }) => signal && cacheApi.getQueries({ signal }),
    queryKey: ['admin', 'cache', 'queries'],
    refetchOnWindowFocus: false,
  });

  if (!queries) {
    return <div>Загрузка...</div>;
  }

  return (
    <Wrapper>
      <Divider>Управление кэшем</Divider>
      <Collapse
        accordion
        items={Object.keys(queries).map((queryGroupName) => ({
          children: <QueryList {...queries[queryGroupName]} />,
          key: queryGroupName,
          label: queryGroupName,
        }))}
      />
    </Wrapper>
  );
}
