import { createForm } from '@felte/solid';
import { Component, createEffect, Match, Switch } from 'solid-js';
import { TextField, Button } from '@kobalte/core';
import reporter from '@felte/reporter-tippy';
import { v4 as uuid } from 'uuid';
import './style.css';
import { useNavigate } from 'solid-start';
import { adminCredentials } from '../credentials';
import { put } from '~/lib/put';
import { del } from '~/lib/del';
import { isFunction } from 'lodash';

interface Props {
  values?: () => any;
}

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

  const getValues = () => {
    if (!isFunction(props?.values)) {
      return null;
    }
    return props.values();
  };

  const isNew = () => !getValues();

  const submitHandler = async (values: any, context: any) => {
    console.log({
      caller: 'User / submitHandler',
      props,
      values,
      context,
    });
    const id = getValues()?._id ?? `user:${uuid()}`;
    await put(id, values, isNew());
    const couchUserId = `org.couchdb.user:${values.username}`;
    const userDoc = {
      _id: couchUserId,
      name: values.username,
      password: values.password,
      type: 'user',
      roles: [],
    };
    await put(couchUserId, userDoc, isNew(), '_users');
    if (isNew()) {
      navigate(`/user/${id}`);
    }
  };

  const cancelHandler = () => {
    navigate(`/user/`);
  };

  const deleteHandler = async () => {
    console.log({
      caller: 'User / deleteHandler',
      id: getValues()?._id,
      props,
    });
    await del(getValues()?._id);
    navigate(`/user/`);
  };

  const validationHandler = async (values: any) => {
    let errors: any = {};
    const credentials = adminCredentials();
    if (!credentials) {
      return errors;
    }
    const { database, username, password } = credentials;
    try {
      const response = await fetch(database, { mode: 'cors' });
      const dbStatus = await response.json();
      if (!dbStatus.couchdb) {
        errors.database = 'The URL is not a couchdb instance';
      }
    } catch (error) {
      errors.database = "Can't access the database";
    }
    if (!!errors.database) {
      return errors;
    }

    if (isNew()) {
      const authString = `${username}:${password}`;
      const headers = new Headers();
      headers.set('Authorization', 'Basic ' + btoa(authString));
      const response = await fetch(
        `${database}/_users/org.couchdb.user:${values.username}`,
        {
          method: 'HEAD',
          mode: 'cors',
          headers,
        }
      );
      if (response.status === 200) {
        errors.username = 'The user is already existing';
      }
    }

    return errors;
  };

  const credentials = adminCredentials();
  const { database } = credentials || { database: null };

  const { form, data, setData, setInitialValues, reset } = createForm({
    onSubmit: submitHandler,
    extend: reporter(),
    validate: validationHandler,
    initialValues: getValues() || { database },
  });

  const createUserHandler = async () => {
    console.log({
      caller: 'User / createUserHandler',
      props,
      data: data(),
    });
    //    setOpenUserNamePasswordDialog(true);
  };

  console.log({
    caller: 'User ',
    props,
    values: getValues(),
  });

  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'
          readOnly={true}
        />
      </TextField.Root>
      <TextField.Root>
        <TextField.Label>User name</TextField.Label>
        <TextField.Input
          type='text'
          name='username'
          required={true}
          placeholder='user name'
          readOnly={!isNew()}
        />
      </TextField.Root>
      <TextField.Root>
        <TextField.Label>Password</TextField.Label>
        <TextField.Input
          type='text'
          name='password'
          required={true}
          placeholder='Password'
          autocomplete='off'
        />
      </TextField.Root>
      <Switch>
        <Match when={!isNew()}>
          <Button.Root type='submit'>Save</Button.Root>
          <Button.Root onclick={deleteHandler}>Delete</Button.Root>
        </Match>
        <Match when={isNew()}>
          <Button.Root type='submit'>Create</Button.Root>
        </Match>
      </Switch>
      <Button.Root onclick={cancelHandler}>Cancel</Button.Root>
    </form>
  );
};

export default User;
