import { defineComponent } from 'vue';

export default defineComponent({
  async setup() {
    definePageMeta({
      middleware: ['authenticate'],
    });

    const credentials = useState(() => ({
      identifier: '',
      password: '',
    }));

    const onSubmit = async (event:Event) => {
      event.preventDefault();

      const { data, error } = await useAsyncGql('login', credentials.value);

      const { setMe } = useMe();
      if (error.value) {
        console.error('Failed to log in!');
        console.error('error:', error.value);
        console.error('data:', data.value);
        setMe(null);
        return;
      }

      useGqlToken({
        token: data.value?.login?.jwt || null,
        config: { type: 'Bearer' },
      });
      setMe(data.value?.login?.user || null);
      navigateTo('/');

    };

    return () => (<div class="sbcms-admin">
      <form
        onSubmit={onSubmit}
      >
        <h1>Login</h1>
        <label>
          Username
          <input
            type="text"
            value={credentials.value.identifier}
            onChange={(event: Event) => {
              credentials.value.identifier = (event.currentTarget as HTMLInputElement).value;
            }}
          />
        </label>
        <label>
          Password
          <input
            type="password"
            value={credentials.value.password}
            onChange={(event: Event) => {
              credentials.value.password = (event.currentTarget as HTMLInputElement).value;
            }}
          />
        </label>
        <button
          type="submit"
        >Log in</button>
      </form>
    </div>);
  },
});
