{% extends "index.html" %}

{% block content %}

<script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script>
<script src="{{ url_for('static', filename='plaid_link.js') }}"></script>

<br>

{% if plaid_items %}
<table>
    <tr>
        <td><u>Institution Name</u></td>
        <td><u>Token Type</u></td>
        <td><u>Connection Status</u></td>
    </tr>
    {% for item in plaid_items %}
        <tr>
            <td>{{ item[0] }}</td>
            <td>{{ item[1] }}</td>
            <td align="center">
                {% if item[2] == True %}
                    <i class="fa-solid fa-check" style="color: green"></i>
                {% elif item[2] == False %}
                    <i class="fa-solid fa-circle-exclamation" style="color: gold"></i>
                {% else %}
                    <i class="fa-solid fa-xmark" style="color: red"></i>
                {% endif %}
            </td>
            <td align="center">
                <button type="button" id="update-account-{{ item[3] }}" {{ 'disabled' if plaid_env != item[1] }}>Update Connection</button>
                <script type="text/javascript">
                    document.getElementById("update-account-{{ item[3] }}").addEventListener("click", (event) => {
                        run_plaid_link("{{ item[3] }}");
                    });
                </script>
            </td>
            <td align="center">
                <button type="button" id="remove-item-{{ item[4] }}" {{ 'disabled' if plaid_env != item[1] }}>Remove Connection</button>
                <script type="text/javascript">
                    document.getElementById("remove-item-{{ item[4] }}").addEventListener("click", (event) => {
                        location.href = "{{ url_for('remove_plaid_item', access_token=item[4], redirect_url=url_for('manage_plaid_items')) | safe }}"
                    })
                </script>
            </td>
        </tr>
    {% endfor %}
</table>

<br>
{% endif %}

<button
type="button"
id="link-account"
class="btn btn-primary btn-dark btn-lg"
style="
        border: 1px solid black;
        border-radius: 5px;
        background: black;
        height: 48px;
        width: 155px;
        margin-top: 5; 
        margin-left: 10;
        color: white;
        font-size: 18px;
    "
>
<strong>Link account</strong>
</button>

<br><br>

<script type="text/javascript">
    const linkToken = "{{ plaid_link_token }}";
    const isOauthRedirect = ("{{ plaid_oauth_redirect }}".toLowerCase() === 'true');
    const redirectUri = isOauthRedirect ? window.location.href : null;
    
    // Start Link when button is clicked
    document.getElementById("link-account").addEventListener("click", (event) => {
        run_plaid_link(linkToken, redirectUri);
    });
</script>

{% endblock %}
