'use client'

import type {FunctionComponent} from 'react'
import {useActionState} from 'react'
import {Label} from '@/components/ui/label'
import {Input} from '@/components/ui/input'
import SubmitButtonWithLoading from '@/components/custom/submitButtonWithLoading'
import {Textarea} from '@/components/ui/textarea'
import type {Contact} from '@/generated/prisma/client'
import type {MeetingWithContact} from '@/models/meetings'
import Combobox from '@/components/custom/combobox'
import DatePicker from '@/components/custom/datePicker'
import ActionButton from '@/components/custom/actionButton'
import {cancelMeetingServerFunction, createMeetingAction, updateMeetingAction} from '@/serverFunctions/meetings'

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

const AddMeetingForm: FunctionComponent<AddContactFormProps> = ({contacts, meeting}) => {
  const [_, createOrUpdateMeeting] = useActionState(meeting?.id ? updateMeetingAction : createMeetingAction, undefined)

  return (
    <>
      <form className="space-y-4" action={createOrUpdateMeeting}>
        {meeting?.id && <input type="hidden" name="id" value={meeting.id} />}
        <div className="grid grid-cols-3 gap-4">
          <div className="col-span-1 flex flex-col gap-4">
            <Label htmlFor="title">Title</Label>
            <Input id="title" type="text" defaultValue={meeting?.title ?? ''} placeholder="Coffee" name="title" />
          </div>
          <div className="col-span-1 flex flex-col gap-4">
            <Label>Contact</Label>
            <Combobox
              initialValue={meeting?.contactId}
              data={[
                ...contacts.map(c => ({
                  label: `${c.firstName} ${c.lastName ?? ''}`,
                  value: c.id,
                })),
              ]}
              label="Choose a contact"
              placeholder="John Doe"
              noResultText="No contacts found"
              name="contactId"
            />
          </div>
          <div className="col-span-1 flex flex-col gap-4">
            <Label>Date</Label>
            <DatePicker name="date" defaultValue={meeting?.date} />
          </div>
        </div>

        <div className="flex flex-col gap-4">
          <Label htmlFor="description">Description</Label>
          <Textarea name="description" rows={5} defaultValue={meeting?.description ?? ''} />
        </div>

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

      {meeting && (
        <ActionButton
          className="my-4 w-full"
          variant="destructive"
          action={() => cancelMeetingServerFunction({id: meeting.id})}
          pendingContent="Canceling meeting ...">
          Cancel meeting
        </ActionButton>
      )}
    </>
  )
}

export default AddMeetingForm
