import { createForm } from '@felte/solid';
import { Component, createUniqueId } from 'solid-js';
import { TextField, Button } from '@kobalte/core';

import './style.css';
import { createServerAction$ } from 'solid-start/server';
import PouchDb from 'pouchdb';
import { v4 as uuid } from 'uuid';

interface Props {}

const Invitation: Component<Props> = (props) => {
  const [saving, save] = createServerAction$(async (values: any) => {
    const db = new PouchDb('.db');
    const id = `invitation/${uuid()}`;
    await db.put({
      _id: id,
      type: 'invitation',
      ...values,
      date: new Date().toISOString(),
    });
    return id;
  });

  const submitHandler = (values: any, context: any) => {
    console.log({
      caller: 'Invitation / submitHandler',
      props,
      values,
      context,
    });
    save(values);
  };

  const { form } = createForm({ onSubmit: submitHandler });

  return (
    <form use:form>
      <TextField.Root>
        <TextField.Label>Mail address</TextField.Label>
        <TextField.Input
          type='mail'
          name='mail'
          required={true}
          placeholder='Email address'
        />
        <TextField.ErrorMessage>
          Please provide a valid URL
        </TextField.ErrorMessage>
      </TextField.Root>
      <TextField.Root>
        <TextField.Label>Database</TextField.Label>
        <TextField.Input
          type='url'
          name='database'
          required={true}
          placeholder='Database URL'
        />
        <TextField.ErrorMessage>
          Please provide a valid URL
        </TextField.ErrorMessage>
      </TextField.Root>
      <TextField.Root>
        <TextField.Label>Password</TextField.Label>
        <TextField.Input
          type='text'
          name='password'
          required={true}
          placeholder='Password'
          autocomplete='off'
        />
        <TextField.ErrorMessage>
          Please provide a valid password
        </TextField.ErrorMessage>
      </TextField.Root>
      <Button.Root type='submit'>Create</Button.Root>
    </form>
  );
};

export default Invitation;
