'use client'

import {FormEventHandler, FunctionComponent, useState} from 'react'
import {Label} from '@/components/ui/label'
import {Input} from '@/components/ui/input'
import {Button} from '@/components/ui/button'
import useServerAction from '@hooks/useServerAction'
import SubmitButtonWithLoading from '@/components/custom/submitButtonWithLoading'
import Actions from '@actions'
import {Profile} from '@/lib/models/users'

const AccountForm: FunctionComponent<Profile> = profile => {
  const [username, setUsername] = useState<string>(profile?.username ?? '')
  const [isUpdating, updateProfile] = useServerAction(Actions.updateProfile)

  const handleFormSubmit: FormEventHandler<HTMLFormElement> = evt => {
    evt.preventDefault()
    // De void operator zorgt er voor dat ESLint geen foutmelding geeft over het gebruik van promises waarvoor geen
    // await, of then en catch gebruikt wordt.
    void updateProfile({username})
  }

  return (
    <form onSubmit={handleFormSubmit} className="space-y-4 mt-4">
      <div className="grid grid-cols-2 gap-4 items-center">
        <Label htmlFor="username">Username</Label>
        <Input type="text" id="username" value={username} onChange={e => setUsername(e.target.value)} />
      </div>

      <SubmitButtonWithLoading loading={isUpdating} text="Update" loadingText="Updating..." />

      <Button
        onClick={evt => {
          evt.preventDefault()
          void Actions.signOut()
        }}
        variant="destructive"
        className="w-full">
        Log out
      </Button>
    </form>
  )
}

export default AccountForm
