'use client'

import type {FunctionComponent} from 'react'
import {useTransition} from 'react'
import {Label} from '@/components/ui/label'
import {Avatar, AvatarImage} from '@/components/ui/avatar'
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'
import {useZodValidatedForm} from '@/lib/useZodValidatedForm'
import Form from '@/components/custom/form'
import FormInput from '@/components/custom/formInput'
import {updateUserSchema} from '@/schemas/userSchemas'

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

  return (
    <Form hookForm={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>

        <FormInput name="username" label="Username" className="mt-2" defaultValue={profile.username} />
      </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
