import AdminRows from '../AdminRows/AdminRows';
import { deleleteQueriesByKey, deleteQuery, getQueries } from '@/api/cache/query';
import type { ResponseQueries } from '@/api/cache/types';
import { useEffect, useState } from 'react';
import type { QueryItem } from 'shared/types/cache';
import styled from 'styled-components';
import { Button } from 'ui/elements';

const Wrapper = styled.div`
  display: flex;
  justify-content: space-between;
  > * {
    &:first-child {
      flex-grow: 1;
    }
  }
`;

export default function AdminTable() {
  const [data, setData] = useState<ResponseQueries>({});

  const handleClick = async (name: string, key: string) => {
    await deleteQuery(key);

    const index = data[name].queries.indexOf(key);
    const updatedQuery: QueryItem = { ...data[name] };

    if (index >= 0 && updatedQuery.queries.length > 1) {
      setData({ ...data, [name]: { ...data[name], queries: data[name].queries.splice(index, 1) } });
    } else if (index === 0) {
      setData({ ...data, [name]: { ...data[name], queries: [] } });
    }
  };

  const handleClickQueriesGroup = async (name: string) => {
    await deleleteQueriesByKey(name);
    if (data[name].queries.length > 0) {
      const updatedQuery = { ...data[name], queries: [] };
      setData({ ...data, [name]: updatedQuery });
    }
  };

  useEffect(() => {
    const getRows = async () => {
      const queryList = await getQueries();

      setData(queryList);
    };

    getRows();
  }, []);

  return (
    <>
      {Object.keys(data).map((key, index) => (
        <Wrapper key={key}>
          <AdminRows
            key={key}
            queries={data[key].queries}
            name={key}
            index={index}
            onClick={handleClick}
          />
          <Button onClick={() => handleClickQueriesGroup(key)}>Удалить все</Button>
        </Wrapper>
      ))}
    </>
  );
}
