'use client'

import type {FunctionComponent} from 'react'
import {useActionState, useTransition} from 'react'
import {Label} from '@/components/ui/label'
import {Avatar, AvatarImage} from '@/components/ui/avatar'
import {Input} from '@/components/ui/input'
import {Button} from '@/components/ui/button'
import SubmitButtonWithLoading from '@/components/custom/submitButtonWithLoading'
import {signOutServerFunction, updateProfileAction} from '@/serverFunctions/users'
import type {Profile} from '@/models/users'
import {Spinner} from '@/components/ui/spinner'

const AccountForm: FunctionComponent<Profile> = profile => {
  const avatarURL = `https://ui-avatars.com/api/?name=${profile.username}&rounded=true}`
  const [_, updateProfile] = useActionState(updateProfileAction, undefined)
  const [transitionPending, startTransition] = useTransition()

  return (
    <form action={updateProfile} className="space-y-4 mt-4">
      <div className="flex gap-2 items-center">
        <Label htmlFor="avatar-upload">
          <Avatar className="h-12 w-12">
            <AvatarImage src={avatarURL} />
          </Avatar>
        </Label>

        <div className="grow flex flex-col gap-2">
          <Label htmlFor="username">Username</Label>
          <Input type="text" id="username" name="username" defaultValue={profile.username ?? ''} />
        </div>
      </div>

      <SubmitButtonWithLoading text="Update" loadingText="Updating..." />

      <Button
        onClick={evt => {
          evt.preventDefault()
          startTransition(signOutServerFunction)
        }}
        disabled={transitionPending}
        variant="destructive"
        className="w-full">
        {transitionPending && <Spinner />} Log out
      </Button>
    </form>
  )
}

export default AccountForm
