'use client'

import type {FormEvent, FunctionComponent} from 'react'
import {useState} from 'react'
import PageTitle from '@/components/custom/pageTitle'
import {Button} from '@/components/ui/button'
import {Dialog, DialogContent, DialogHeader, DialogTitle} from '@/components/ui/dialog'
import {Label} from '@/components/ui/label'
import {Input} from '@/components/ui/input'
import SubmitButtonWithLoading from '@/components/custom/submitButtonWithLoading'
import LinedCircleIconButton from '@/components/custom/linedCircleIconButton'
import {Plus} from 'lucide-react'
import {useArrayState} from '@/hooks/useArrayState.ts'
import {useCreateContact} from '@/api/contactApi.ts'

const AddContactForm: FunctionComponent = () => {
  const [open, setOpen] = useState(false)
  const [firstName, setFirstName] = useState('')
  const [lastName, setLastName] = useState('')
  const [contactInfo, setContactInfo, updateContactInfoItem] = useArrayState<{type: string; value: string}>([
    {type: '', value: ''},
  ])
  const {mutateAsync: createContact, isPending} = useCreateContact()

  const addContact = async (evt: FormEvent<HTMLFormElement>) => {
    evt.preventDefault()
    await createContact({firstName, lastName, contactInfo})
    setOpen(false)
    setFirstName('')
    setLastName('')
    setContactInfo([{type: '', value: ''}])
  }

  return (
    <>
      <div className="flex justify-between items-center mb-6">
        <PageTitle>My contacts</PageTitle>
        <Button onClick={() => setOpen(true)}>Add New Contact</Button>
      </div>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent aria-describedby={undefined}>
          <DialogHeader>
            <DialogTitle>Add New Contact</DialogTitle>
          </DialogHeader>
          <form className="space-y-4" onSubmit={evt => void addContact(evt)}>
            <div className="flex gap-4">
              <div className="flex-grow">
                <Label htmlFor="name">Firstname</Label>
                <Input
                  id="name"
                  type="text"
                  value={firstName}
                  onChange={evt => setFirstName(evt.target.value)}
                  placeholder="John"
                />
              </div>
              <div className="flex-grow">
                <Label htmlFor="name">Lastname</Label>
                <Input
                  id="name"
                  type="text"
                  value={lastName}
                  onChange={evt => setLastName(evt.target.value)}
                  placeholder="Doe"
                />
              </div>
            </div>
            <div className="flex flex-col gap-4">
              <Label>Contactinfo</Label>

              {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"
                  />
                </div>
              ))}

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

            <div className="flex justify-end">
              <SubmitButtonWithLoading pending={isPending} loadingText="Creating contact" text="Create" />
            </div>
          </form>
        </DialogContent>
      </Dialog>
    </>
  )
}

export default AddContactForm
