<script lang="ts">
  import {Profile, ProfileBuilder} from "@welshman/domain"
  import {pubkey, profilesByPubkey} from "@app/welshman"
  import AltArrowLeft from "@assets/icons/alt-arrow-left.svg?dataurl"
  import {errorMessage} from "@lib/util"
  import Icon from "@lib/components/Icon.svelte"
  import Button from "@lib/components/Button.svelte"
  import Spinner from "@lib/components/Spinner.svelte"
  import ProfileEditForm from "@app/components/ProfileEditForm.svelte"
  import {clearModals} from "@app/modal"
  import {pushToast} from "@app/toast"
  import {updateProfile} from "@app/profiles"

  // The edit form binds to plain mutable fields (name/about/nip05/picture), so we
  // hand it a plain values object rather than a Profile Reader. A Reader exposes its
  // raw parsed content as `.values`; a fresh profile starts from an empty builder.
  const reader = $profilesByPubkey.get($pubkey!)
  const profile = reader instanceof Profile ? {...reader.values} : new ProfileBuilder().update({}).values
  const initialValues = {profile}

  const back = () => history.back()

  // TODO(welshman-migration): `profile` here is a plain values object (the form binds
  // mutable fields), not a Profile Reader. It is typed Profile to match ProfileEditForm's
  // Values type and updateProfile's signature, both of which still say Profile; updateProfile
  // routes a non-Reader through `new ProfileBuilder().update(profile)`. Confirm the intended
  // values vs Reader contract once the shared types settle.
  const onsubmit = async ({profile}: {profile: Profile}) => {
    loading = true

    try {
      // TODO(welshman-migration): updateProfile is async (returns Promise<Thunk>); the old
      // waitForThunkError shim did not await its arg. Awaiting the thunk first before
      // .waitForError() — confirm this matches intended behavior.
      const error = await (await updateProfile({profile})).waitForError()

      if (error) {
        pushToast({
          theme: "error",
          message: `Failed to update your profile: ${errorMessage(error)}`,
        })
      } else {
        pushToast({message: "Your profile has been updated!"})
        clearModals()
      }
    } finally {
      loading = false
    }
  }

  let loading = $state(false)
</script>

<ProfileEditForm {initialValues} {onsubmit}>
  {#snippet footer()}
    <Button class="btn btn-link" onclick={back}>
      <Icon icon={AltArrowLeft} />
      Go Back
    </Button>
    <Button type="submit" class="btn btn-primary" disabled={loading}>
      <Spinner {loading} />
      Save Changes
    </Button>
  {/snippet}
</ProfileEditForm>
