'use client'

import {FormEvent, FunctionComponent, useState} from 'react'
import {Label} from '@/components/ui/label'
import {Input} from '@/components/ui/input'
import Actions from '@actions'
import SubmitButtonWithLoading from '@/components/custom/submitButtonWithLoading'
import useServerAction from '@hooks/useServerAction'
import {Contact} from '@prisma/client'
import Combobox from '@/components/custom/combobox'
import {Textarea} from '@/components/ui/textarea'
import DatePicker from '@/components/custom/datePicker'
import {MeetingWithContact} from '@/lib/models/meetings'

interface AddContactFormProps {
  contacts: Contact[]
  meeting?: MeetingWithContact
}

const AddContactForm: FunctionComponent<AddContactFormProps> = ({contacts, meeting}) => {
  const [title, setTitle] = useState(meeting?.title ?? '')
  const [description, setDescription] = useState(meeting?.description ?? '')

  const [firstName, setFirstName] = useState('')
  const [lastName, setLastName] = useState('')
  const [contactId, setContactId] = useState<string | null>(meeting?.contactId ?? null)
  const [isCreating, createContact] = useServerAction(Actions.createMeetings)
  const [isUpdating, updateContact] = useServerAction(Actions.updateMeetings)
  const [isCancelling, cancelMeeting] = useServerAction(Actions.deleteMeeting)
  const isPending = isCreating || isUpdating
  const [date, setDate] = useState<Date | undefined>(meeting?.date)

  const addContact = async (evt: FormEvent<HTMLFormElement>) => {
    evt.preventDefault()
    const contactData = {
      title,
      description,
      date: date ?? new Date(), // default to today
      contact: contactId
        ? contactId
        : {
            firstName,
            lastName,
          },
    }
    await (meeting?.id ? updateContact({...contactData, id: meeting.id}) : createContact(contactData))
  }

  return (
    <>
      <form className="space-y-4" onSubmit={addContact}>
        <div className="grid grid-cols-3 gap-4">
          <div className="col-span-1">
            <Label htmlFor="title">Title</Label>
            <Input
              id="title"
              type="text"
              value={title}
              onChange={evt => setTitle(evt.target.value)}
              placeholder="Coffee"
            />
          </div>
          <div className="col-span-1">
            <Label>Contact</Label>
            <Combobox
              initialValue={meeting?.contactId}
              data={[
                ...contacts.map(c => ({
                  label: `${c.firstName} ${c.lastName ?? ''}`,
                  value: c.id,
                })),
                {label: 'Create new contact', value: 'new'},
              ]}
              onValueChange={x => {
                if (x === 'new') {
                  setContactId(null)
                } else {
                  setContactId(x)
                }
              }}
              label="Choose a contact"
              placeholder="John Doe"
              noResultText="No contacts found"
            />
          </div>
          <div className="col-span-1">
            <Label>Date</Label>
            <DatePicker onDateChange={setDate} initialValue={date} />
          </div>
        </div>

        <div>
          <div className="grid grid-cols-2 gap-4">
            <div className="col-span-1">
              <Label htmlFor="firstname">Contact's firstname</Label>
              <Input
                id="firstname"
                type="text"
                disabled={contactId !== null}
                value={firstName}
                onChange={evt => setFirstName(evt.target.value)}
                placeholder="John"
              />
            </div>
            <div className="col-span-1">
              <Label htmlFor="lastname">Contact's lastname</Label>
              <Input
                id="lastname"
                type="text"
                disabled={contactId !== null}
                value={lastName}
                onChange={evt => setLastName(evt.target.value)}
                placeholder="Doe"
              />
            </div>
          </div>
          <div className="text-gray-300">Choose "Create new contact" in the contact combobox to add a new contact.</div>
        </div>

        <div>
          <Label htmlFor="description">Description</Label>
          <Textarea rows={5} value={description} onChange={evt => setDescription(evt.target.value)} />
        </div>

        <SubmitButtonWithLoading
          disabled={isCancelling}
          loading={isPending}
          loadingText={meeting ? 'Updating contact' : 'Creating contact'}
          text={meeting ? 'Update' : 'Create'}
        />
      </form>

      {meeting && (
        <form
          className="my-4"
          onSubmit={evt => {
            evt.preventDefault()
            void cancelMeeting(meeting.id)
          }}>
          <SubmitButtonWithLoading
            loading={isCancelling}
            text="Cancel meeting"
            loadingText="Canceling meeting..."
            variant="destructive"
          />
        </form>
      )}
    </>
  )
}

export default AddContactForm
