import ReloadOutlined from '@ant-design/icons/lib/icons/ReloadOutlined';
import Button from 'client/Elements/Button';
import { PrimaryText } from 'client/Elements/Text';
import { useStores } from 'client/hooks/useStores';
import { Flex } from 'client/UIKit/grid';
import { useState } from 'react';
import { ElementStatus } from 'types/elements';
import { resetIns } from '../../lib/resetIns';
import validate from '../../lib/validation';

const TopControls = ({ title, insType, fetchData, validation }) => {
  const [isPending, setIsPending] = useState(false);
  const { calculationStore } = useStores();

  const handleGetData = () => {
    const validationRes = validate.call(calculationStore, validation);
    if (!validationRes) return;

    resetIns.call(calculationStore, insType);
    setIsPending(true);
    fetchData.call(calculationStore).finally(() => {
      setIsPending(false);
    });
  };

  return (
    <Flex alignItems="center" justifyContent="space-between" mb="5px">
      <PrimaryText>{title}</PrimaryText>
      <Button
        shape="circle"
        status={isPending ? ElementStatus.Loading : ElementStatus.Default}
        action={handleGetData}
        icon={<ReloadOutlined />}
      />
    </Flex>
  );
};

export default TopControls;
