import logging
from typing import Optional

from matplotlib import pyplot as plt


def save_plot(save_plots: bool, filepath: str, plot: plt, name: Optional[str], file_format: str = "png"):
    """
    This method saves the generated plot to a file.

    Parameters
    ----------
    save_plots: bool
        A boolean flag to determine whether to save the plot or not.
    filepath: str
        The path to the directory where the plot will be saved.
    plot: plt
        The matplotlib.pyplot instance.
    name: str
        The name of the file to which the plot will be saved (if self.save_plots is True).
    file_format: str
        The file format in which plot will be saved. By default, it is 'png'.

    Returns
    -------
    None
    """

    if save_plots:
        output_path = f"{filepath}{name}.{file_format}"
        plot.savefig(output_path, bbox_inches="tight", dpi=300)
        plot.show()
        plot.close()
        logging.info(f"Plot saved at {output_path}")
    else:
        plot.show()
