from matplotlib.patches import Arc
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

def draw_pitch(ax, fig):
    linecolor = "black"
    width = 68
    length = 105

    # Outline
    plt.plot([length/2, length], [width, width], color=linecolor)
    plt.plot([length, length], [width, 0], color=linecolor)
    plt.plot([length, length/2], [0, 0], color=linecolor)
    circle = plt.Circle((length / 2, width / 2), 8, color=linecolor, fill=False)
    ax.add_patch(circle)

    # Goal
    plt.plot([length + 2, length], [(width / 2 - 7.32 / 2), (width / 2 - 7.32 / 2)], color=linecolor)
    plt.plot([length + 2, length+2], [(width / 2 + 7.32 / 2), width / 2 - 7.32 / 2], color=linecolor)
    plt.plot([length + 2, length], [(width / 2 + 7.32 / 2), (width / 2 + 7.32 / 2)], color=linecolor)

    # Box
    plt.plot([(length - 16.5), length], [(width / 2 + 16.5), (width / 2 + 16.5)], color=linecolor)
    plt.plot([(length - 16.5), (length - 16.5)], [(width / 2 + 16.5), (width / 2 - 16.5)], color=linecolor)
    plt.plot([(length - 16.5), length], [(width / 2 - 16.5), (width / 2 - 16.5)], color=linecolor)

    # SmallBox
    plt.plot([length, length - 5.5], [(width / 2 + 7.32 / 2 + 5.5), (width / 2 + 7.32 / 2 + 5.5)], color=linecolor)
    plt.plot([length - 5.5, length - 5.5], [(width / 2 + 7.32 / 2 + 5.5), width / 2 - 7.32 / 2 - 5.5], color=linecolor)
    plt.plot([length - 5.5, length], [width / 2 - 7.32 / 2 - 5.5, width / 2 - 7.32 / 2 - 5.5], color=linecolor)

    centre_spot = plt.Circle((length / 2, width / 2), 0.4, color=linecolor)
    ax.add_patch(centre_spot)

    pen_spot = plt.Circle((length - 11, width / 2), 0.2, color=linecolor)
    ax.add_patch(pen_spot)

    # Prepare Arc
    arc = Arc((length - 11, width / 2), height=18.3, width=18.3, angle=0, theta1=128, theta2=232, color=linecolor)

    ax.add_patch(arc)

    plt.xlim(length/2, length+3)

    plt.gca().set_aspect('equal')

    # Add the color scale to the right side of the pitch
    min_value = 0.0
    max_value = 0.3
    num_colors = 100
    cmap = plt.get_cmap('autumn_r')
    norm = mcolors.Normalize(vmin=min_value, vmax=max_value)

    # Create a dummy mappable object
    mappable = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
    mappable.set_array([])

    # Position the color scale vertically on the right side of the pitch
    cax = fig.add_axes([0.9, 0.25, 0.03, 0.5])
    cb = plt.colorbar(mappable=mappable, ticks=[min_value, max_value], cax=cax)
    cb.ax.set_yticklabels([f'{min_value}', f'{max_value}'], color='black')

    return fig, ax

