<template>
  <v-dialog v-model="dialog">
    <v-btn slot="activator">
      {{ buttonText }}
    </v-btn>

    <v-card>
      <v-form
        ref="form"
        v-model="valid"
        @submit.prevent="validate"
        lazy-validation
      >
        <slot></slot>

        <v-divider></v-divider>

        <v-card-actions>
          <v-spacer></v-spacer>

          <v-btn color="success" type="submit" :disabled="!valid">
            {{ buttonText }}
          </v-btn>

          <v-btn color="error" @click.native="dialog = false">
            Cancel
          </v-btn>
        </v-card-actions>
      </v-form>
    </v-card>
  </v-dialog>
</template>

<script>
export default {
  name: 'FormDialog',
  data: () => ({
    dialog: false,
    valid: true
  }),

  props: {
    buttonText: String
  },

  methods: {
    validate() {
      if (this.$refs.form.validate()) {
        this.$emit('confirm')
      }
    }
  },

  watch: {
    dialog(val) {
      if (val) {
        requestAnimationFrame(() => {
          this.$parent.$refs.autofocus.focus()
        })
      } else {
        this.$refs.form.resetValidation()
      }
    }
  }
}
</script>
