'use client'
import type {FunctionComponent} from 'react'
import {useTransition} from 'react'
import {Button} from '@/components/ui/button'
import {Loader2, Plus, Trash} from 'lucide-react'
import {Textarea} from '@/components/ui/textarea'
import LinedCircleIconButton from '@/components/custom/linedCircleIconButton'
import SubmitButtonWithLoading from '@/components/custom/submitButtonWithLoading'
import {deleteContactServerFunction, updateContactAction} from '@/serverFunctions/contacts'
import type {Contact} from '@/generated/prisma/client'
import {useZodValidatedForm} from '@/lib/useZodValidatedForm'
import {updateContactSchema} from '@/schemas/contactSchemas'
import {useFieldArray, useWatch} from 'react-hook-form'
import Form from '@/components/custom/form'
import FormInput from '@/components/custom/formInput'
import AvatarWithFallback from '@/components/custom/avatarWithFallback'

const ContactDetailForm: FunctionComponent<Contact> = contact => {
  const [form, updateContact] = useZodValidatedForm(updateContactSchema, updateContactAction, {
    defaultValues: {
      ...contact,
    },
  })
  const contactInfo = useFieldArray({control: form.control, name: 'contactInfo'})
  const contactInfoData = useWatch({control: form.control, name: 'contactInfo'})

  // De useTransition hook wordt gebruikt om een server function op te roepen (waarna deze een server action genoemd
  // wordt). De isPending variabele geeft aan of er een transition bezig is, en de startTransition functie wordt
  // gebruikt om een nieuwe transition te starten.
  // State updates die binnen een transition worden gedaan, worden pas doorgevoerd nadat alle transition afgehandeld
  // zijn, als een gebruiker snel 20 keer op een knop drukt, worden er dus 20 transitions uitgevoerd en wordt de state
  // pas aangepast als alle 20 transitions zijn afgehandeld.
  const [isPending, startTransition] = useTransition()

  return (
    <Form hookForm={form} action={updateContact}>
      <input type="hidden" name="id" value={contact.id} />
      <div className="flex items-center">
        <AvatarWithFallback
          avatar={contact.avatar}
          firstName={contact.firstName}
          lastName={contact.lastName}
          className="-mt-2"
        />
        <div className="text-4xl ms-4 flex-grow">
          <div className="flex gap-4 me-4">
            <FormInput name="firstName" label="Firstname" placeholder="John" />
            <FormInput name="lastName" label="Lastname" />
          </div>
        </div>
      </div>

      <div className="text-muted-foreground my-4">
        <Textarea name="description" defaultValue={contact.description ?? ''} placeholder="Description" />
      </div>

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

      <div className="flex flex-col gap-4 my-4">
        {contactInfo.fields.map((_, i) => (
          <div className="flex gap-4" key={i}>
            <FormInput name={`contactInfo.${i}.type`} placeholder="Contact type (e.g. email, phone)" />
            <FormInput name={`contactInfo.${i}.value`} placeholder="Contact info" />
            <Button
              variant="ghost"
              onClick={evt => {
                evt.preventDefault()
                contactInfo.remove(i)
              }}>
              <Trash />
            </Button>
          </div>
        ))}
      </div>

      <LinedCircleIconButton
        Icon={Plus}
        disabled={contactInfoData?.at(-1)?.type === '' || contactInfoData?.at(-1)?.value === ''}
        onClick={evt => {
          evt.preventDefault()
          contactInfo.append({type: '', value: ''})
        }}
      />

      <div className="flex flex-col gap-4 mt-4">
        <SubmitButtonWithLoading loadingText="Updating contact..." text="Update contact" />
        <Button
          variant="destructive"
          className="w-full"
          disabled={isPending}
          onClick={evt => {
            // Prevent the form from submitting.
            evt.preventDefault()
            startTransition(() => deleteContactServerFunction({id: contact.id}))
          }}>
          {isPending && <Loader2 className="animate-spin" />} Delete contact
        </Button>
      </div>
    </Form>
  )
}

export default ContactDetailForm
