import { createForm } from '@felte/solid';
import { Component, createEffect, Match, Show, Switch } 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';
import { put } from '~/lib/db';
import { useNavigate } from 'solid-start';

interface Props {
  values?: any;
}

const Invitation: Component<Props> = (props) => {
  const navigate = useNavigate();

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

  const submitHandler = async (values: any, context: any) => {
    console.log({
      caller: 'Invitation / submitHandler',
      props,
      values,
      context,
    });
    const id = await save({ values, props });
    if (!props.values) {
      navigate(`/invitations/${encodeURIComponent(id)}`);
    }
  };

  let { form } = createForm({
    onSubmit: submitHandler,
    initialValues: props?.values,
  });

  console.log({
    caller: 'Invitation ',
    props,
  });

  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'>
        <Switch fallback={<>Create</>}>
          <Match when={!!props.values}>Save</Match>
        </Switch>
      </Button.Root>
    </form>
  );
};

export default Invitation;
