<script lang="ts">
  import { toggleFollow } from '$lib/Data/AniList/follow';
  import type { AniListAuthorisation } from '$lib/Data/AniList/identity';
  import LogInRestricted from '$lib/Error/LogInRestricted.svelte';

  interface Props {
    user: AniListAuthorisation;
  }

  let { user }: Props = $props();

  let input = $state('');
  let submit = $state('');
</script>

{#if user === undefined}
  <LogInRestricted />
{:else}
  <p>
    <!-- svelte-ignore missing_declaration -->
    <input
      type="text"
      minlength="1"
      placeholder="Username"
      bind:value={input}
      onkeypress={(e) => {
        if (e.key === 'Enter') {
          submit = input;

          // eslint-disable-next-line no-undef
          umami.track('Fix Follow');
        }
      }}
    />
    <a href={'#'} onclick={() => (submit = input)}>
      Toggle follow for {input.length === 0 ? '...' : input}
    </a>
  </p>

  {#if submit.length > 0}
    {#await toggleFollow(user, submit)}
      Toggling follow ...
    {:then response}
      <p>
        Successfully toggled follow for {submit}.

        {submit}
        {response.isFollower ? 'is' : 'is not'} following you, {response.isFollowing
          ? 'but'
          : 'and'} you {response.isFollowing ? 'are' : 'are not'} following them.
      </p>
    {:catch}
      <p>Failed to toggle follow for {submit}.</p>
    {/await}
  {/if}
{/if}
