'use client'
import {FormEvent, FunctionComponent, useState} from 'react'
import {Avatar, AvatarImage} from '@/components/ui/avatar'
import {Button} from '@/components/ui/button'
import Actions from '@actions'
import {Plus, Trash} from 'lucide-react'
import {useArrayState} from '@hooks/useArrayState'
import {Textarea} from '@/components/ui/textarea'
import {Input} from '@/components/ui/input'
import LinedCircleIconButton from '@/components/custom/linedCircleIconButton'
import SubmitButtonWithLoading from '@/components/custom/submitButtonWithLoading'
import useServerAction from '@hooks/useServerAction'
import {ContactWithInfoObject} from '@/lib/models/contacts'

const ContactDetailForm: FunctionComponent<ContactWithInfoObject> = contact => {
  const [firstName, setFirstName] = useState<string>(contact.firstName ?? '')
  const [lastName, setLastName] = useState<string>(contact.lastName ?? '')
  const [description, setDescription] = useState<string>(contact.description ?? '')
  const [contactInfo, setContactInfo, updateContactInfoItem, deleteContactInfoItem] = useArrayState<{
    type: string
    value: string
  }>(contact.contactInfo)
  const [isPending, updateContact] = useServerAction(Actions.updateContact)

  const submitHandler = async (evt: FormEvent) => {
    evt.preventDefault()

    await updateContact({
      id: contact.id,
      firstName,
      lastName,
      description,
      contactInfo,
    })
  }

  return (
    <form onSubmit={submitHandler}>
      <div className="flex items-center">
        <Avatar className="h-18 w-18">
          <AvatarImage src={contact.avatar ?? `https://ui-avatars.com/api/?name=${firstName}`} />
        </Avatar>
        <div className="text-4xl ms-4 flex-grow">
          <div className="flex gap-4 me-4">
            <div className="flex-grow">
              <Input
                id="name"
                type="text"
                value={firstName}
                onChange={evt => setFirstName(evt.target.value)}
                placeholder="John"
              />
            </div>
            <div className="flex-grow">
              <Input
                id="name"
                type="text"
                value={lastName}
                onChange={evt => setLastName(evt.target.value)}
                placeholder="Doe"
              />
            </div>
          </div>
        </div>
      </div>

      <div className="text-muted-foreground my-4">
        <Textarea value={description} onChange={evt => setDescription(evt.currentTarget.value)} />
      </div>

      <div className="text-xl">Contactinfo</div>

      <div className="flex flex-col gap-4 my-4">
        {contactInfo.map(({type, value}, i) => (
          <div className="flex gap-4" key={i}>
            <Input
              id="name"
              type="text"
              className="flex-grow"
              value={type}
              onChange={evt => updateContactInfoItem(i, {type: evt.target.value, value})}
              placeholder="Contact type (e.g. email, phone)"
            />
            <Input
              id="name"
              type="text"
              className="flex-grow"
              value={value}
              onChange={evt => updateContactInfoItem(i, {type, value: evt.target.value})}
              placeholder="Contact info"
            />
            <Button
              variant="ghost"
              onClick={evt => {
                evt.preventDefault()
                deleteContactInfoItem(i)
              }}>
              <Trash />
            </Button>
          </div>
        ))}
      </div>

      <LinedCircleIconButton
        Icon={Plus}
        disabled={contactInfo?.at(-1)?.value === '' || contactInfo?.at(-1)?.type === ''}
        onClick={() => setContactInfo(old => [...old, {type: '', value: ''}])}
      />

      <div className="flex flex-col gap-4 mt-4">
        <SubmitButtonWithLoading loading={isPending} loadingText="Updating contact..." text="Update contact" />
        <Button
          variant="destructive"
          className="w-full"
          onClick={evt => {
            // Prevent the form from submitting.
            evt.preventDefault()
            void Actions.deleteContact(contact.id)
          }}>
          Delete contact
        </Button>
      </div>
    </form>
  )
}

export default ContactDetailForm
