import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faCheckCircle, faSpinner, faXmarkCircle } from "@fortawesome/free-solid-svg-icons"
import { useMetadata, useMutateMetadata } from "../profile/hooks/useMetadata"
import { useState, useEffect } from 'react'

export default function UserMetadata() {


  const { status, data, error, isFetching, isPending } = useMetadata()
  const mutateMetadata = useMutateMetadata()


  const username = `${data?.metadata?.first_name || ''} ${data?.metadata?.last_name || ''}`.trim();
  const { metadata } = data || {};

  const [ isUsernamePublic, setIsUsernamePublic ] = useState(metadata?.isUsernamePublic || false)
  useEffect(() => {
    mutateMetadata.mutate({ isUsernamePublic })
  }, [ isUsernamePublic ])

  return (
    <>
      
      {isPending && <FontAwesomeIcon icon={faSpinner} className="fa-spin-pulse mr-2"></FontAwesomeIcon>}
      
      <div className="box">
        <span className="mr-2">Display {username} publicly?</span>
        <input className="mr-2" type="checkbox" checked={isUsernamePublic} onChange={(evt) => setIsUsernamePublic(evt.target.checked)}/> 
        {(mutateMetadata.status === 'success') && <FontAwesomeIcon color="lime" icon={faCheckCircle}></FontAwesomeIcon>}
        {(mutateMetadata.status === 'pending') && <FontAwesomeIcon icon={faSpinner}></FontAwesomeIcon>}
        {(mutateMetadata.status === 'error') && <FontAwesomeIcon color="red" icon={faXmarkCircle}></FontAwesomeIcon>}
      </div>
    </>
  )
}


