'use client'

import type {FunctionComponent} from 'react'
import {Plus} from 'lucide-react'
import SubmitButtonWithLoading from '@/components/custom/submitButtonWithLoading'
import LinedCircleIconButton from '@/components/custom/linedCircleIconButton'
import PageTitle from '@/components/custom/pageTitle'
import Link from 'next/link'
import {Button} from '@/components/ui/button'
import {createContactAction} from '@/serverFunctions/contacts'
import {useZodValidatedForm} from '@/lib/useZodValidatedForm'
import {createContactSchema} from '@/schemas/contactSchemas'
import Form from '@/components/custom/form'
import FormInput from '@/components/custom/formInput'
import {useFieldArray, useWatch} from 'react-hook-form'

const Page: FunctionComponent = () => {
  const [form, createContact] = useZodValidatedForm(createContactSchema, createContactAction, {
    defaultValues: {
      contactInfo: [{value: '', type: ''}],
    },
  })
  const contactInfo = useFieldArray({control: form.control, name: 'contactInfo'})
  const contactInfoData = useWatch({control: form.control, name: 'contactInfo'})

  return (
    <>
      <PageTitle>New Contact</PageTitle>
      <Form hookForm={form} className="mt-4 space-y-4" action={createContact}>
        <div className="flex gap-4">
          <FormInput name="firstName" label="First name" placeholder="John" />
          <FormInput name="lastName" label="Last name" placeholder="Doe" />
        </div>
        <div className="flex flex-col gap-2">
          <h5 className="text-xl">Contactinfo</h5>

          {contactInfo.fields.map((_, i) => (
            <div className="flex gap-2" key={i}>
              <FormInput name={`contactInfo.${i}.type`} placeholder="Contact type (e.g. email, phone)" />
              <FormInput name={`contactInfo.${i}.value`} placeholder="Contact info" />
            </div>
          ))}

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

        <div className="flex justify-end mb-2">
          <SubmitButtonWithLoading loadingText="Creating contact" text="Create" />
        </div>
      </Form>

      <Link href="/contacts">
        <Button variant="destructive" className="w-full">
          Cancel
        </Button>
      </Link>
    </>
  )
}

export default Page
