import type {FormEvent, FunctionComponent} from 'react'
import {useState} from 'react'
import {useArrayState} from '@/hooks/useArrayState.ts'
import {useDeleteContact, useGetContact, useUpdateContact} from '@/api/contactApi.ts'
import {useNavigate, useParams} from 'react-router'
import {Avatar, AvatarImage} from '@/components/ui/avatar.tsx'
import {Input} from '@/components/ui/input.tsx'
import {Textarea} from '@/components/ui/textarea.tsx'
import {Button} from '@/components/ui/button.tsx'
import {Plus, Trash} from 'lucide-react'
import LinedCircleIconButton from '@/components/custom/linedCircleIconButton.tsx'
import SubmitButtonWithLoading from '@/components/custom/submitButtonWithLoading.tsx'

const ContactDetailForm: FunctionComponent = () => {
  const {id} = useParams()
  const {data: contact} = useGetContact(id!)
  const {mutateAsync: updateContact, isPending: isUpdating} = useUpdateContact()
  const {mutateAsync: deleteContact, isPending: isDeleting} = useDeleteContact()
  const isPending = isUpdating || isDeleting
  const navigate = useNavigate()

  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 submitHandler = async (evt: FormEvent) => {
    evt.preventDefault()

    await updateContact({
      id: contact.id,
      userId: contact.userId,
      firstName,
      lastName,
      description,
      contactInfo,
    })
    navigate('/')
  }

  return (
    <form onSubmit={evt => void submitHandler(evt)}>
      <div className="flex items-center">
        <Avatar className="h-18 w-18">
          <AvatarImage src={contact.avatar} />
        </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 pending={isPending} loadingText="Updating contact..." text="Update contact" />
        <Button
          variant="destructive"
          className="w-full"
          onClick={evt => {
            // Prevent the form from submitting.
            evt.preventDefault()
            void deleteContact(contact.id).then(() => navigate('/'))
          }}>
          Delete contact
        </Button>
      </div>
    </form>
  )
}

export default ContactDetailForm
