<script lang="ts">
  import {
    apiError,
    isApiDown,
    clearApiError,
    setApiError,
  } from "../helperModules/GlobalVariablesAndHelperFunctions.svelte";
  import { CheckIfAniListLoggedInAndLoadWatchList } from "../helperModules/CheckIfAniListLoggedInAndLoadWatchList.svelte";
  import { CheckIfMALLoggedInAndSetUser } from "../helperModules/CheckIfMyAnimeListLoggedIn.svelte";
  import { CheckIfSimklLoggedInAndSetUser } from "../helperModules/CheckIsSimklLoggedIn.svelte";
  import { Modal, Button } from "flowbite-svelte";
  let showModal = false;
  $: if ($apiError) {
    showModal = true;
  }
  async function handleRetry() {
    const service = $apiError?.service;
    clearApiError();

    try {
      if (service === "anilist") {
        await CheckIfAniListLoggedInAndLoadWatchList();
      } else if (service === "mal") {
        await CheckIfMALLoggedInAndSetUser();
      } else if (service === "simkl") {
        await CheckIfSimklLoggedInAndSetUser();
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : String(err);
      setApiError(
        service || "unknown",
        `Retry failed: ${errorMsg}`,
        undefined,
        true,
      );
    }
  }
  function handleDismiss() {
    clearApiError();
    showModal = false;
  }
</script>

{#if showModal && $apiError}
  <Modal
    open={showModal}
    title="{$apiError.service.toUpperCase()} API Error"
    size="md"
  >
    <div class="space-y-4">
      <div class="p-4 bg-red-50 border border-red-200 rounded-lg">
        <p class="text-red-800 font-medium">{$apiError.message}</p>
        {#if $apiError.statusCode}
          <p class="text-red-600 text-sm mt-2">
            Status: {$apiError.statusCode}
          </p>
        {/if}
      </div>
      <p class="text-gray-600">
        The application will remain open. You can retry the connection or
        dismiss this message to continue with limited functionality.
      </p>
    </div>
    <div slot="footer" class="flex gap-3 justify-end">
      {#if $apiError.canRetry}
        <Button on:click={handleRetry} class="bg-blue-600 hover:bg-blue-700">
          Retry Connection
        </Button>
      {/if}
      <Button on:click={handleDismiss} color="alternative">Dismiss</Button>
    </div>
  </Modal>
{/if}
